Mongoose查询是否可以使用if else?

5

我有这个数据结构:

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项目ID和数量到购物车中。
否则(则该项已存在):$inc数量加1。
问题:如何实现这个结果?我需要做两个单独的查询吗?如果可能的话,我想避免这样做。

也许这可以帮到你?https://dev59.com/JJffa4cB1Zd3GeqP503R - Jeremy Thille
2个回答

1
我浏览了他们所有的更新字段操作符,可能没有办法以我想要的方式完成这个操作。
我想知道为什么更新操作符中没有$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();
        }
});

0

这种逻辑不应该出现在数据库查询中,而应该在应用程序层中处理。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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接