我在node.js中使用MongoDB
我想要的是将文档添加到集合中。该文档具有唯一的ID,一个lastAccess字段(用于存储上次访问的日期)和一个timesAccessed字段,在创建文档时应将其设置为0,如果更新则应增加1。
我试过了:
// coll is a valid collection
coll.update(
{user: accountInfo.uid},
{user: accountInfo.uid,
lastAccess: new Date(),
$inc: {timesAccessed: 1},
$setOnInsert: {timesAccessed: 0}
},
{upsert: true, w: 1},
function(err, result) {
if (err) throw err;
console.log("Record upserted as " + result);
});
但是节点说:
MongoError: Modifiers and non-modifiers cannot be mixed
什么是巧而又安全的方法?
您应该$ set值或更新/替换整个对象。因此,无论update(find_query, completely_new_object_without_modifiers, ...)
或update(find_query, object_with_modifiers, ...)
另外,您不能使用相同的字段名来$ set和$ setOnInsert,因此您将从1开始计数:)哦,您不需要将find_query项目添加到update_query,它们将被自动添加。
尝试:
col1.update( {
user: accountInfo.uid
}, {
$set: {
lastAccess: new Date()
}
$inc: {
timesAccessed: 1
}
}, {
upsert: true,
w: 1
}, function(err, result) {
if(err) {
throw err;
}
console.log("Record upsert as", result);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句