Mongoose upsert不会创build默认模式属性

示例文档架构:

var CompanySchema = Schema({ created: { type: Date, default: Date.now }, modified: { type: Date, default: Date.now }, address: { type: String, required:true }, name: { type: String, required:true } }); 

我正在使用通用的请求处理程序来编辑和创build“公司”文档:

 exports.upsert = function(req, res) { helper.sanitizeObject(req.body); var company = { name: req.body.name, address: req.body.address }; var id = req.body.id || new mongoose.Types.ObjectId(); var queryOptions = { upsert: true }; Company.findByIdAndUpdate(id, company, queryOptions).exec(function(error, result) { if(!error) { helper.respondWithData(req, res, { data: result.toJSON() }); } else { helper.respondWithError(req, res, helper.getORMError(error)); } }); }; 

但是使用这种方法,当插入一个新的文档时, created modified属性不会保存为默认值Date.now 。 现在我可以调用Company.create根据id的存在,但我想知道为什么upsert不使用默认值,如果一个属性不存在于一个新的文档?

我正在使用Mongoose版本〜3.8.10,

发生什么事情是,在调用任何“更新”方法系列(如findByIdAndUpdate时,都不会使用Mongoose的validation,中间件或默认值。 他们只能通过调用来savecreate

原因在于“更新”调用是有效地传递给本地驱动程序的,Mongoose只根据模式定义提供字段的types转换。

mongoose4.0更新

Mongoose现在支持在update期间创build新文档时设置默认值, findOneAndUpdatefindByIdAndUpdate upsert。 将setDefaultsOnInsert选项设置为true以启用此选项。 这使用$setOnInsert运算符来创build插入时的默认值。

 var queryOptions = { upsert: true, setDefaultsOnInsert: true }; Company.findByIdAndUpdate(id, company, queryOptions).exec( ... 

您可以使用{ "$setOnInsert": { value: 31 } } Doc

参考: https : //groups.google.com/forum/#!topic/ mongoose-orm/ WuJSqxPX8T8

语法: findOneAndUpdate([query], [doc], [options], [callback]) Doc

例:

 model.findOneAndUpdate( { username: 'john' }, { "$setOnInsert": { points: '0' }, $push: { "boards": { "account":req.body.account, "game":req.body.game } } { upsert: true}, function(err, doc) { });