我有一个模式:
const guestSchema = new Schema({
id: String,
cart: [
{
product: {
type: mongoose.Schema.ObjectId,
ref: "products"
},
quantity: Number
}
]
});我有一个疑问:
Guest.findOneAndUpdate(
{ id: req.sessionID },
{
$cond: [
{ "cart.product": { $ne: req.body.itemID } },
{ $push: { "cart": { product: req.body.itemID, quantity: 1 } } },
{ $inc: { "cart.quantity": 1 } }
]
},
{ upsert: true, new: true }
).exec(function(err, docs) {
err ? console.log(err) : res.send(docs);
});基本上,我想要做的是根据条件进行更新。我试过使用$cond,但发现操作符并不像我正在做的那样用于查询。
在此基础上:
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }对于我的查询,我想要类似于这个操作符的功能。
,让我们打破我的条件:
对于我的布尔表达式:我想检查req.body.itemID对于我的购物车中的任何值是否是$ne
如果是这样的话:将$push itemID和quantity放到购物车中
Else (然后项已经存在):$inc的数量为1
问题:如何实现这一结果?我需要分开两次查询吗?如果可能的话,我尽量避免那样做
发布于 2018-03-23 22:00:50
我查看了他们所有的更新字段操作符,而且可能没有办法以我想要的方式完成这个任务。
我想知道为什么没有用于更新操作符的$cond。尽管如此,我还是有了我想要的功能实现的解决方案。只是不像我喜欢的那样优雅。
Guest.findOneAndUpdate(
{ id: req.sessionID },
{ id: req.sessionID }, //This is here in case need to upsert new guest
{ upsert: true, new: true }
).exec(function(err, docs) {
if (err) {
console.log(err);
} else {
//Find the index of the item in my cart
//Returns (-1) if not found
const item = doc.cart.findIndex(
item => item.product == req.body.itemID
);
if (item !== -1) {
//Item found, so increment quantity by 1
doc.cart[item].quantity += 1;
} else {
//Item not found, so push into cart array
doc.cart.push({ product: req.body.itemID, quantity: 1 });
}
doc.save();
}
});发布于 2018-03-23 18:42:09
这种类型的逻辑不属于数据库查询。它应该发生在应用层。MongoDB在检索和更新单个记录时使用索引也非常快,因此这不应该引起关注。
请试着做这样的事情:
try {
const guest = await Guest.findOne().where({
id: req.sessionID
}).exec();
// your cond logic, and update the object
await guest.save();
res.status(200).json(guest);
} catch (error) {
handleError(res, error.message);
}https://stackoverflow.com/questions/49449179
复制相似问题