我在使用 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);
}
库/ Controller
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 );
现在我们看一下mongoose方法的用法.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) {
您尝试使用“ native ”收集方法,而不是使用 Mongoose 已存在的收集方法。此外,这还显示了需要传递给此方法的正确参数,这些参数在提供的文档链接中进行了进一步解释。
另请参阅.findByIdAndUpdate()
以及其他方法,它们是 .findAndModify()` 方法的基本变体。
关于node.js - 在 Node.js 中使用 findAndModify 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987978/