Mongoose中Task.update回调的numberAffected与raw参数是否有效?
numberAffected and raw returning NaN/undefined in Mongoose's Task.update callback? Great question—this issue boils down to Mongoose version differences that changed the callback signature for update operations. Let's break it down clearly:
Are numberAffected and raw valid parameters?
They are valid... but only in older Mongoose versions (≤4.x). In Mongoose 5.x and later, the callback structure for update methods was completely revised, which is why you're seeing NaN and undefined in your logs.
What changed between versions?
Mongoose ≤4.x: The
update()method's callback used three parameters:Task.update(filter, update, function(err, numberAffected, rawResponse) { // numberAffected = count of documents modified // rawResponse = raw MongoDB driver response });If you were using an older version, your code would work as expected.
Mongoose ≥5.x: The callback now only takes two parameters:
errandresult. Theresultis an object containing metadata about the operation, including:n: Number of documents matchednModified: Number of documents actually updatedok: Boolean indicating if the operation succeeded- Other driver-specific properties
Your current code is trying to access
numberAffectedas the second parameter, which is now theresultobject—not a number. When you log%dwith an object, you getNaN, and the third parameter (raw) doesn't exist anymore, so it'sundefined.
Fixing your code
Update your callback to use the new parameter structure. Here's the corrected version:
var Task = require('../models/task.js'); exports.update = function(req, res) { Task.update({ contents : req.body.contents }, { status : req.body.status }, function(err, result) { if (err) { throw err; } console.log('The number of updated documents was %d', result.nModified); console.log('The raw response from MongoDB was', result); }); res.redirect('/'); res.end(); };
Bonus: Use modern syntax and safer methods
Mongoose 5.x+ also recommends using updateOne() or updateMany() explicitly (instead of the generic update(), which is an alias for updateMany()) to avoid accidentally updating multiple documents. Here's an async/await version for better readability:
var Task = require('../models/task.js'); exports.update = async function(req, res) { try { const result = await Task.updateOne( { contents : req.body.contents }, { status : req.body.status } ); console.log('The number of updated documents was %d', result.nModified); console.log('The raw response from MongoDB was', result); } catch (err) { console.error(err); } res.redirect('/'); res.end(); };
内容的提问来源于stack exchange,提问作者Riddle Aaron

