Mongodb 如果可能,是否使用Mongoose查询?
我有这个模式:Mongodb 如果可能,是否使用Mongoose查询?,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我有这个模式: const guestSchema = new Schema({ id: String, cart: [ { product: { type: mongoose.Schema.ObjectId, ref: "products" }, quantity: Number } ] }); 我有一个疑问: Guest.findOneAndUpdate( { id: req.s
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> ] }
{$cond:[,]}
我希望在查询中使用类似于此运算符的功能
让我们来分析一下我的情况:
对于布尔表达式:我想检查req.body.itemID
是否是$ne
到我购物车中的任何值
如果为true,则:$push
将项目ID和数量放入购物车
Else(则项目已存在):$inc
数量增加1
问题:如何实现这一结果?我需要做两个独立的查询吗?如果可能的话,我会尽量避免这样做这种逻辑不属于数据库查询。它应该发生在应用层。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);
}
我看了他们所有的照片,可能没有办法按照我想要的方式来做
我想知道为什么没有更新操作符的$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();
}
});
也许这能帮到你?