如何通过node.js mongodb驱动程序向现有集合添加验证程序?
下面是我试图向现有集合添加验证程序的代码如何通过node.js mongodb驱动程序向现有集合添加验证程序?,node.js,mongodb,Node.js,Mongodb,下面是我试图向现有集合添加验证程序的代码 const { MongoClient } = require("mongodb") const schema = { $jsonSchema: { bsonType: "object", additionalProperties: false, required: ["name"], properties: { _id: { bsonType: "objectId" },
const { MongoClient } = require("mongodb")
const schema = {
$jsonSchema: {
bsonType: "object",
additionalProperties: false,
required: ["name"],
properties: {
_id: {
bsonType: "objectId"
},
name: {
bsonType: "string"
}
}
}
}
const main = async () => {
const client = await MongoClient.connect(
"mongodb://localhost",
{ useNewUrlParser: true }
)
const db = client.db("t12")
// await db.createCollection("test", { validator: schema })
await db.createCollection("test")
await db.admin().command({ collMod: "test", validator: schema })
await db.collection("test").createIndex({ name: 1 }, { unique: true })
await db.collection("test").insertOne({ name: "t1" })
await db.collection("test").insertOne({ value: "t2" }) // should fail
const all = await db
.collection("test")
.find({})
.toArray()
console.log(all)
await client.close()
}
main().catch(err => console.error(err))
它失败了:
max7z@mbp t12__npm__mongodb (master)*$ node test/1.js
{ MongoError: ns does not exist
at /Users/max7z/projects/t/t12__npm__mongodb/node_modules/mongodb-core/lib/connection/pool.js:581:63
at authenticateStragglers (/Users/max7z/projects/t/t12__npm__mongodb/node_modules/mongodb-core/lib/connection/pool.js:504:16)
at Connection.messageHandler (/Users/max7z/projects/t/t12__npm__mongodb/node_modules/mongodb-
ok: 0,
errmsg: 'ns does not exist',
code: 26,
codeName: 'NamespaceNotFound',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }
^C
如果我使用该模式创建集合,它会工作,但是当我试图通过collMod添加vatidator时,它会失败
如何通过collMod命令将验证器添加到现有集合?我认为应该使用Mongoose来验证模式。请阅读关于月亮女神的文章。这是最好的选择。问题就在这一行:
wait db.admin()命令({collMod:“test”,validator:schema})
正确的方法是:
wait db.command({collMod:“test”,validator:schema})
我创建了如下函数
const updateValidator = async (collectionName, newValidator) => {
return db.command({
collMod: collectionName,
validator: newValidator,
validationLevel: "moderate",
validationAction: "warn"
});
}
db.command
的问题在于它替换了整个验证模式。因此,您需要访问集合的当前架构。由于我在nodejs库中没有找到该函数,我添加了将其作为参数传递的可能性
在我的例子中,我是从另一个迁移模块获得它的。例如
const currentValidator = require("migration-file-where-I-defined-the-previous-schema").schema.validator;
在所需文件中,我有一些初始模式,如:
module.exports.schema = {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name"],
properties: {
name: {
bsonType: "string",
maxLength: 300,
minLength: 3,
description: "Must be a string and is required"
},
created: {
bsonType: "date",
description: "Date when it was created"
},
deleted: {
bsonType: "date",
description: "Date when it was deleted"
}
}
},
}
};
然后我创建一个新模式的合并,这就足够了。例如
const updatedValidator = Object.assign({}, currentValidator);
updatedValidator.$jsonSchema.properties.new_attribX = {
enum: ["type1", "type2"],
description: "State of the tenant related to its life cycle"
};
updatedValidator.$jsonSchema.required.push('new_attribX');
updateValidator("mycollection", updatedValidator)
.then(next)
.catch(console.error);
这将用应用更改的新模式替换以前的模式。对我来说,这已经足够了,但请记住,当您有需要使用新数据更新的现有数据时,您需要使用以下内容来更新它们
collection.updateMany({'new_attribX': {$exists : false}}, {$set: {'new_attribX': 'type1'}});
对于没有该属性的数据(new\u attribX
),它应该将它们添加到这种初始默认值中:type1
我希望它能有所帮助。我熟悉Mongoose,但我想使用原生mongodb驱动程序。问题是这将替换模式,而不是更新模式。