用Mongoose返回更新的集合
我使用nodejs / express / mongoose / angularjs。 我想更新一个名为Lists的集合,它有几个属性,其中之一是一个项目的数组。 在下面的代码中,我正在推送项目数组中的新任务项目。 一切工作正常,但更新function不会发回更新的集合,那么我必须对数据库执行另一个查询。 有没有更有效的方法来做到这一点?
nodejs / express代码:
exports.addTaskToList = function(req, res) { var listId = req.params.Id; var taskId = req.params.TaskId; Lists.update({_id: listId}, {$push: {items: taskId}}, {safe:true, upsert: true}, function(err, result){ if(err) { console.log('Error updating todo list. ' + err); } else{ console.log(result + ' todo list entry updated - New task added'); Lists.findById(listId).populate('items').exec(function (err, updatedEntry) { if (err) { console.log('Unable to retrieve todo list entry.'); } res.send(JSON.stringify(updatedEntry)); }); } }); };
此外,数组项是一个ObjectIds数组。 这些项目是在一个单独的模式,所以在一个单独的集合。 是否有可能推动整个对象,而不仅仅是它的_id,以便没有创build另一个集合?
更新方法 不会返回更新的文档:
但是,如果我们不需要在我们的应用程序中返回的文档,并且只想直接更新数据库中的属性,那么Model#更新就适合我们。
如果您需要更新并退回文档,请考虑以下选项之一:
传统方法:
Lists.findById(listId, function(err, list) { if (err) { ... } else { list.items.push(taskId) list.save(function(err, list) { ... }); } });
更短的方法:
Lists.findByIdAndUpdate(listId, {$push: {items: taskId}}, function(err, list) { ... });
使用findOneAndUpdate()方法,并在查询参数中使用选项为{“new”:true}
return this.sessionModel .findOneAndUpdate({user_id: data.user_id}, {$set:{session_id: suuid}}, { "new": true}) .exec() .then(data=>{ return { sid: data.session_id } })
关于你最后的问题:
是否有可能推动整个对象,而不仅仅是它的_id,以便没有创build另一个集合?
答案是肯定的。 您可以使用Mongoose轻松地将子文档存储在文档中( 有关子文档的文档 )。 通过稍微改变你的模式,你可以把你的整个项目对象(不只是项目_id
)推送到List模式中定义的项目数组中。 但是你需要修改你的模式,例如:
var itemSchema = new Schema({ // Your Item schema goes here task: 'string' // For example }); var listSchema = new Schema({ // Your list schema goes here listName: String, // For example... items: [itemSchema] // Finally include an array of items });
通过将item
对象添加到列表的items
属性,然后保存该列表 – 您的新项目将被持久化到List集合。 例如,
var list = new List({ listName: "Things to do" }); list.items.push({ task: "Mow the lawn" }); list.save(function(error, result) { if (error) // Handle error console.log(result.list) // Will contain your item instance });
所以当你加载你的列表时, items
属性会预先填充你的项目数组。
这是因为项目将不再坚持它一个单独的集合。 它将被坚持List列表作为列表的子文档。