Mrugesh Thaker Mrugesh Thaker - 7 months ago 129
Node.js Question

findOneAndUpdate with push array elements gives error in mongoose

My query is as shown below:

const updateLikes = (item_id, userInfo) => {
return new Promise((resolve, reject) => {
itemLike.findOneAndUpdate({ 'item_id': item_id }, { $inc: { no_of_likes: 1 } }, { "$push": { "users": userInfo } }, { 'new': true }, (err, info) => {
if (err) {
reject(err);
} else {
if (info) {
resolve();
} else {
reject('no item found');
}
}
});
});
};


itemLike.js

const itemLike = new Schema({
item_id: { type: mongoose.Schema.ObjectId, ref: 'items', index: true },
no_of_likes: { type: Number, default: 0 },
users: [{ type: mongoose.Schema.ObjectId, ref: 'user' }]
}, { versionKey: false });


module.exports = mongoose.model('item_like', itemLike);


As soon as I execute this query , I get the error as shown below:

events.js:160
throw er; // Unhandled 'error' event
^

TypeError: callback.apply is not a function
at Query.<anonymous> (C:\Users\anand\quFlipApi\node_modules\mongoose\lib\model.js:3702:16)
at C:\Users\anand\quFlipApi\node_modules\kareem\index.js:273:21
at C:\Users\anand\quFlipApi\node_modules\kareem\index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)


Am I missing anything here?

Answer Source

Looking at the docs for findOneAndUpdate, you're providing one too many parameters.

It should be conditions, update, options, callback. You're getting an error because Mongoose is trying to invoke { 'new': true } as the callback function.

It looks like your update definition has been split into two objects by mistake. You need to remove the braces highlighted in bold below.

{ $inc: { no_of_likes: 1 } }, { "$push": { "users": userInfo } }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download