在Node.js中使用findAndModify错误

我有困难的时候使用findAndModify 。 这是我的代码和错误:

 var userSchema = new Schema({ incr: Number, practicename: String, basicinformation: [ { recordno: String, firstname: String, middlename: String, lastname: String, gender: String, dateofbirth: Date, dateofdeath: Date, socialsecurityno: String, status: String, updateddate: Date, updatedby: String } ], userSchema.statics.findAndModify = function (query, sort, doc, options, callback) { return this.collection.findAndModify(query, sort, doc, options, callback); } 

LIB /控制器

 var query = { update: { $inc: { incr: 1 } }, upsert: true }; User.findAndModify(query, function (err, users) { if (err) return res.send(500) if (!err) console.log(users) }); 

错误: –

 Error: Illegal sort clause, must be of the form [['field1', '(ascending|descendi ng)'], ['field2', '(ascending|descending)']] at Object.exports.formattedOrderClause (D:\Projects\project1\node_modules\mongoose\node_modules\mongodb\lib\mongodb\utils.js:41:1 1) at Collection.findAndModify (D:\Projects\project1 

首先,摆脱这个代码,因为你不需要它,你实际上定义了一个你甚至没有使用的“静态”签名:

 userSchema.statics.findAndModify = function (query, sort, doc, options, callback) { return this.collection.findAndModify(query, sort, doc, options, callback); } 

你应该有一个你的User模型的声明是这样的:

 var User = mongoose.model( "User", userSchema ); 

现在我们来看一下.findOneAndUpdate()方法.findOneAndUpdate()的用法:

 User.findOneAndUpdate( { _id: userid }, // this is what "query" means { "$inc": { "incr": 1 } }, // this is what "update" means { "upsert": true }, // this is what "options" means function(err,user) { 

您正在尝试使用“本地”收集方法,而不是使用Mongoose已经存在的方法。 此外,这显示了需要传递给此方法的正确参数,这些参数将在提供的文档链接中进一步解释。

另请参阅.findByIdAndUpdate()和其他方法,它们是.findByIdAndUpdate()方法的基本变体。

您可以尝试使用mongoose findByIdAndUpdate方法

 Model.findByIdAndUpdate( id, { $set: {name: 'xyz'}} , { new:true}, function(err,result) { if ( err ) { console.warn(err); } else { console.log(result); } }); 

选项new:true返回更新的文档,否则返回旧的未更新的文档