【发布时间】:2012-04-30 15:20:04
【问题描述】:
我正在 Node 中创建一个包含一些 CRUD 组件的应用程序。在我的一个数据对象上,我有一个 save() 方法,如果对象具有在集合中找到的 id,则更新记录,如果没有,则更新插入新文档。此外,如果进行 upsert,我想取回 Mongo 生成的文档的 _id。
似乎findAndModify 会这样做,而且确实会从数据库返回一个_id 值。在我的查询子句中,我按 _id 过滤。如果我的数据对象没有 id,Mongo 会正确执行 upsert,但是,无论它返回什么 _id 值,除了我在 update 子句中设置的键之外,它还会在根据我在query 子句中使用的值创建文档。为了清楚起见,一些代码:
User.prototype.save = function(callback) {
var that = this;
var args = {
'query' : { _id: this.getId() }, //getId() returns empty string if not set
'update' : { $set : {
firstName : this.firstName,
lastName : this.lastName,
email : this.email
//_id : this.getId()
// which is blank, is magically getting added due to query clause
}},
'new' : true,
'upsert' : true,
'fields' : {'_id' : true}
};
this.db.collection(dbName).findAndModify(args, function(err, doc){
if(!that.getId()) {
that.setId(doc._id);
}
if (typeof(callback) === "function"){
callback.call(that);
}
});
}
我只是在寻找更新的语义,它也恰好在 upsert 上返回 Mongo 生成的 _id。我不希望额外附加 query 子句的值,就好像它们在 update 映射中一样。有什么方法可以实现我的目标吗?
【问题讨论】:
标签: javascript node.js mongodb