我正在尝试根据条件进行推送或拉取,以及更新插入
myCollection.update(
{'id': location},
{
$set: { count },
$setOnInsert: {
id: location,
users: []
},
},
{
$cond: {
if: (increment==1),
then: {$push: { users: userToken }},
else: {$pull: { users: userToken }}
}
},
{'upsert':true},
(err, data) => {
...
我正在尝试将其干燥(有效):
mongo.connect(dbUrl, (err, db) => {
if (err) throw err
let myCollection = db.collection('myCollection')
if(increment==1){
myCollection.update(
{'id': location},
{
$set: { count },
$push: { users: userToken },
$setOnInsert: {
id: location
}
},
{'upsert':true},
(err, data) => {
if (err) throw err
console.log(data);
callback()
db.close()
}
)
}
else{
myCollection.update(
...
$pull: { users: userToken },
...
)
}
})
当我有 $cond 时,它不会向数据库添加任何内容。 $cond 应该在哪里?
最佳答案
<强> $cond
在这里不适用,但在聚合框架中适用。您需要的是一个纯旧的原生 JS 条件语句,您可以在更新操作中使用它之前创建更新文档,当然这应该在条件 block 中设置。考虑以下示例:
let queryObj = { 'id': location },
usersObj = { 'users': userToken },
updateObj = {
'$set': { count },
'$setOnInsert': queryObj
},
options = { 'upsert': true },
updateOperator = '$pull';
if (increment == 1) updateOperator = '$push';
updateObj[updateOperator] = usersObj;
myCollection.update(queryObj, updateObj, options,
(err, data) => {
if (err) throw err
console.log(data);
callback();
db.close();
}
)
关于javascript - 如何使用 upsert :true 在 MongoDB 更新中 $cond $push/$pull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424987/