Mongoose request, if possible?

I have this circuit:

const guestSchema = new Schema({
  id: String,
  cart: [
    {
      product: {
        type: mongoose.Schema.ObjectId,
        ref: "products"
      },
      quantity: Number
    }
  ]
});

I have this query:

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);
});

Basically, what I'm trying to do is conditional update. I tried to use $cond, but found out that the operator is not used for queries, as I do.

Based on this:

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

I want something similar to the functionality of this statement for my request.

Let me break my condition:

For my boolean expression: I want to check if req.body.itemID $neany of the values ​​in my cart matches

If true, then: $pushitemID and quantity in the cart

Else (then the item already exists): $incquantity by 1

Question: How to achieve this result? Do I need to make two separate requests? I try to avoid this if possible

+4
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);
}
0

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();
        }
});
0

Source: https://habr.com/ru/post/1695239/


All Articles