添加一个字段到现有的MongoDB文档(在Node.js中使用Mongoose)

我在MongoDB数据库的一个集合Article中有这个已有的文档:

 [ { site: 'www.atlantico.fr', date: '2014-05-27T11:10:19.000Z', link: 'http://www.atlantico.fr/example.html', _id: 538473817eb00f082f4803fc, __v: 0} ] 

我想在Node.js中使用Mongoose来为这个文档添加一个新的字段day'example' 。 所以我这样做:

 Article.update( { link: 'http://www.atlantico.fr/example.html'}, { $set : {day : 'example'} }, function(err){ }); 

但它不起作用,因为当我查询文档后,没有新的字段day出现…

在Mongoose中使用update$set时,我一定犯了一个错误,但是我找不到我的错误。

我错过了什么? 谢谢!

尝试

 Article.update( {link: 'http://www.atlantico.fr/example.html'}, {day : 'example' }, {multi:true}, function(err, numberAffected){ }); 

并且不要忘记将模式添加到模式。

 Article.findByIdAndUpdate(id, { $set: { day: 'example' }}, { new: true }, function (err, article) { if (err) return handleError(err); res.send(article); }); 

我更喜欢这种方式,因为它包含一个callback函数。

参考和更多信息: http : //mongoosejs.com/docs/documents.html