【问题标题】:Mongoose query using if else possible?如果可能的话,使用猫鼬查询?
【发布时间】:2018-09-02 02:27:01
【问题描述】:

我有这个架构:

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

问题:如何实现这个结果?我需要进行两个单独的查询吗?如果可能的话,我会尽量避免这样做

【问题讨论】:

标签: mongodb mongoose mongodb-query


【解决方案1】:

我浏览了他们所有的Update Field Operators,可能没有办法以我想要的方式做到这一点。

我想知道为什么更新运算符没有$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();
        }
});

【讨论】:

    【解决方案2】:

    这种类型的逻辑不属于数据库查询。它应该发生在应用层。 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-08
      • 2012-02-03
      • 2014-03-03
      • 2019-02-18
      • 2015-11-28
      • 1970-01-01
      • 2020-06-02
      • 2020-07-12
      相关资源
      最近更新 更多