Mat*_*hyn 3 mongoose mongodb node.js
我有以下架构
var Schema = new mongoose.Schema({
type: {required: true, type: String, enum: ["device", "beacon"], index: true},
device: {
type: {type: String},
version: {type: String},
model: {type: String}
},
name: String,
beaconId: {required: false, type: mongoose.Schema.Types.ObjectId},
lastMeasuredTimestamp: {type: Number, index: true},
lastMeasuredPosition: {type: [Number], index: "2dsphere"},
lastMeasuredFloor: {type: Number, index: true}
}, {strict: false});
Run Code Online (Sandbox Code Playgroud)
请注意,我已将严格设置为 false。这是因为将架构中未定义的自定义属性添加到文档是有效的。
接下来我做以下查询
DB.Document.update({_id: "SOME_ID_HERE"}, {$set: {type: "bull"}}, {runValidators: true})
这会将属性“type”更改为根据 Mongoose 架构无效的值。我使用 runValidators 选项来确保运行模式验证。
但是,此查询的最终结果是“type”更改为“bull”并且不运行验证。但是,当我将严格设置为 true 时,验证确实运行并(正确)显示了错误。
为什么严格会影响验证是否运行?当我查看这个描述http://mongoosejs.com/docs/guide.html#strict 时,它只提到严格限制添加未在架构中定义的属性(我不想要这个特定架构的东西)。
安装信息:
经过一番尝试,我找到了一个有效的解决方案。如果未来的 Mongoose 用户遇到同样的问题,我会将其发布在这里。
诀窍是save在 Mongoose 文档上使用该方法。出于某种原因,这确实可以正确运行验证器,同时还允许使用严格选项。
因此,更新文档的基本过程如下所示:
Model.findOnesave文档。在代码中:
// Find the document you want to update
Model.findOne({name: "Me"}, function(error, document) {
if(document) {
// Merge the document with the updates values
merge(document, newValues);
document.save(function(saveError) {
// Whatever you want to do after the update
});
}
else {
// Mongoose error or document not found....
}
});
// Merges to objects and writes the result to the destination object.
function merge(destination, source) {
for(var key in source) {
var to = destination[key];
var from = source[key];
if(typeof(to) == "object" && typeof(from) == "object")
deepMerge(to, from);
else if(destination[key] == undefined && destination.set)
destination.set(key, from);
else
destination[key] = from;
}
}
Run Code Online (Sandbox Code Playgroud)