我如何知道Mongoose addToSet实际上添加了什么?

我有一个包含项目的数据库,每个项目都有一个链接数组。 添加链接时,我的express.js代码是这样的:

router.get('/links/add', function(req, res){ Project.findOneAndUpdate( {_id: req.query.pid}, {$addToSet: {links: {url: req.query.url , title: req.query.title} }}, {safe: true, upsert: true, new:true}, function(err, project) { if(err) { //do stuff } else { //Something was added to set! } } ); }); 

它工作得很好,不添加重复,但我需要知道什么时候实际更新。 现在,你可以看到我已经启用了new:true选项,它返回新文档,所以我可以删除它,看看链接是否存在于旧版本,但有没有办法做到这一点启用标志?

这似乎是一个基本的function,但我无法find任何文件。

既然你正在添加到一个集合,我们将find该集合,然后检查我们的更新值是否在集合中。 如果是这样,我们可以结束这个function,否则我们可以在更新内容的同时更新。 (这是主旨,可能有一两个错误,因为我自己无法testing)。

 router.get('/links/add', function(req, res){ var updating = false; Project.find({_id: req.query.pid}, function(err, project) { if(err) { // handle error } else { // Check if found project contains what we mean to update. // If it does already (nothing is changing) leave updating as false // and we exit. // Otherwise keep reference to what is being updated, set updating to // true, and after we finish updating you have reference to what changed } } if(updating) { Project.findOneAndUpdate( {_id: req.query.pid}, {$addToSet: {links: {url: req.query.url , title: req.query.title} }}, {safe: true, upsert: true, new:true}, function(err, project) { if(err) { //do stuff } else { //Something was added to set! } } ); } });