mongoose:不能更新保存callback

我有这个mongoose模式:

var UrlSchema = new mongoose.Schema({ description: String }); 

然后,我创build一个模型:

 var newUrl = new Url({ "description": "test" }); newUrl.save(function (err, doc) { if (err) console.log(err); else{ Url.update({_id: doc._id},{description: "a"}); } }); 

但任何更新执行…为什么? 谢谢

您需要将callback添加到更新方法或调用#exec()来执行更新:

 var newUrl = new Url({ "description": "test" }); newUrl.save(function (err, doc) { if (err) console.log(err); else{ Url.update({_id: doc._id},{description: "a"}, function (err, numAffected) { // numAffected should be 1 }); // --OR-- Url.update({_id: doc._id},{description: "a"}).exec(); } }); 

只是供参考:我个人远离update因为它绕过默认,setter,中间件,validation等,这是主要原因使用像mongooseODM的主要原因。 我只使用update处理私人数据(无用户input)和自动递增值。 我会重写为:

 var newUrl = new URL({ "description": "test" }); newUrl.save(function(err, doc, numAffected) { if (err) console.log(err); else { doc.set('description', 'a'); doc.save(); } });