Reputation: 9746
I am having tough time using findAndModify
. Here is my code & error :-
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/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 :-
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
Upvotes: 1
Views: 5260
Reputation: 6781
you can try mongoose findByIdAndUpdate method instead
Model.findByIdAndUpdate( id, { $set: {name: 'xyz'}} , { new:true}, function(err,result) {
if ( err ) {
console.warn(err);
} else {
console.log(result);
}
});
the option new:true
returns the updated document, else the old unupdated document
Upvotes: 1
Reputation: 151220
First of all, get rid of this code as you do not need it and you are actually defining a "static" signature that you are not even using:
userSchema.statics.findAndModify = function (query, sort, doc, options, callback) {
return this.collection.findAndModify(query, sort, doc, options, callback);
}
You should have a declaration for your User
model that is something like this:
var User = mongoose.model( "User", userSchema );
Now let's look at the usage of the mongoose method .findOneAndUpdate()
in long form:
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) {
You were trying to use the "native" collection method rather than the same that already exists using Mongoose. Also this shows the correct arguments that that need to be passed to this method that are further explained in the documentation link provided.
Also see .findByIdAndUpdate()
and other methods that are basic variations of the .findAndModify()` method.
Upvotes: 3