0
let bulk = Card.collection.initializeOrderedBulkOp();
// if user doesn't exist in array
bulk.find({
'_id': mongoose.Types.ObjectId(card_id),
'likedBy': { '$ne': mongoose.Types.ObjectId(user_id) }
}).updateOne({
'$inc': { 'likes': 1 },
'$push': { 'likedBy': mongoose.Types.ObjectId(user_id) }
});
// if user exists in array
bulk.find({
"_id": mongoose.Types.ObjectId(card_id),
"likedBy": mongoose.Types.ObjectId(user_id)
}).updateOne({
"$inc": { "likes": -1 },
"$pull": { "likedBy": mongoose.Types.ObjectId(user_id) }
});
bulk.execute(function(response) {
console.log(response);
return res.json({
'state': true,
'msg': 'Successful',
})
});
上面/不喜欢MongoDB是应该通过递增或如果likedBy
阵列中存在的用户ID递减所述likes
字段的行为。像使用批量
但是,两个函数都运行,因此最后一个批量将成为最后一个操作。在上面,最终结果总是为零。
我怀疑查询总是匹配文档,因此.updateOne()
部分运行在所有。
这里的模式:
var CardSchema = new Schema({
slug: {
type: String,
lowercase: true,
index: true
},
title: String,
content: String,
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
},
options: [],
likedBy: [],
likes: Number,
createdBy: String,
featured: Boolean,
});
有没有更好的蒙戈的方式做喜欢/不喜欢的事情吗?
我认为你误解了[如何用MongoDB建模“喜欢”投票系统](https://stackoverflow.com/q/28006521/2313887)。你说的行为是“互相取消”,因为第一个是“喜欢”,第二个是“不喜欢”。你不打算一次提交“两个”操作。他们的意图是独立的每一个行动。 –
在我的用户界面中,我有一个按钮,其目的是让它在喜欢/不喜欢之间交替。因此,第一次点击,就像。点击下一个,不喜欢等等。检查链接。 – Rexford