如果字段不在模式中,如何使猫鼬失败?
How to make mongoose fail if field is not in schema?
如果我尝试使用不在架构中的字段保存文档,我希望 mongoose 失败。
我知道 strict
选项 (https://mongoosejs.com/docs/guide.html#strict),但它不能满足我的需求。 strict: true
在没有警告的情况下删除字段。并且 strict: false
允许保存所有内容(从长远来看这并不好)。
var thingSchema = new Schema({..}, { /* ?? */ })
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save();
有没有办法提供一些选项,以便 thing.save();
因错误而失败?
我想为本地开发打开这个选项。这样我就可以在不进行硬调试的情况下找到拼写错误和遗忘的字段
更新回答:
下列猫鼬 v5.3.14
是正确的。他们可能会在未来的版本中更改它。
请记住,"strict": "throw"
并未涵盖所有情况。大多数 create/update 操作将抛出:
const model = new Model({ name: 'Mario', iAmNotInTheSchema: true })
await Model.create({ name: 'Mario', iAmNotInTheSchema: true })
await Model.updateOne({}, { iAmNotInTheSchema: true })
await Model.updateMany({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { $set: { iAmNotInTheSchema: true } })
错误信息很好:
Field `iAmNotInTheSchema` is not in schema and strict mode is set to throw.
但对于这种情况:
const model = await Model.findOne({})
model.iAmNotInTheSchema = true
await model.save()
不会抛出。代码运行没有任何错误,iAmNotInTheSchema 将被忽略(与 strict: true
一样)。
The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data.
有一个选项传递给架构构造函数以在这种情况下抛出错误。参考:https://mongoosejs.com/docs/guide.html#strict
new Schema({..}, {"strict": "throw"});
如果我尝试使用不在架构中的字段保存文档,我希望 mongoose 失败。
我知道 strict
选项 (https://mongoosejs.com/docs/guide.html#strict),但它不能满足我的需求。 strict: true
在没有警告的情况下删除字段。并且 strict: false
允许保存所有内容(从长远来看这并不好)。
var thingSchema = new Schema({..}, { /* ?? */ })
var Thing = mongoose.model('Thing', thingSchema);
var thing = new Thing({ iAmNotInTheSchema: true });
thing.save();
有没有办法提供一些选项,以便 thing.save();
因错误而失败?
我想为本地开发打开这个选项。这样我就可以在不进行硬调试的情况下找到拼写错误和遗忘的字段
更新回答:
下列猫鼬 v5.3.14
是正确的。他们可能会在未来的版本中更改它。
请记住,"strict": "throw"
并未涵盖所有情况。大多数 create/update 操作将抛出:
const model = new Model({ name: 'Mario', iAmNotInTheSchema: true })
await Model.create({ name: 'Mario', iAmNotInTheSchema: true })
await Model.updateOne({}, { iAmNotInTheSchema: true })
await Model.updateMany({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { iAmNotInTheSchema: true })
await Model.findOneAndUpdate({}, { $set: { iAmNotInTheSchema: true } })
错误信息很好:
Field `iAmNotInTheSchema` is not in schema and strict mode is set to throw.
但对于这种情况:
const model = await Model.findOne({})
model.iAmNotInTheSchema = true
await model.save()
不会抛出。代码运行没有任何错误,iAmNotInTheSchema 将被忽略(与 strict: true
一样)。
The strict option may also be set to "throw" which will cause errors to be produced instead of dropping the bad data.
有一个选项传递给架构构造函数以在这种情况下抛出错误。参考:https://mongoosejs.com/docs/guide.html#strict
new Schema({..}, {"strict": "throw"});