首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果可能的话使用猫鼬查询?

如果可能的话使用猫鼬查询?
EN

Stack Overflow用户
提问于 2018-03-23 11:57:58
回答 2查看 4.1K关注 0票数 5

我有一个模式:

代码语言:javascript
复制
const guestSchema = new Schema({
  id: String,
  cart: [
    {
      product: {
        type: mongoose.Schema.ObjectId,
        ref: "products"
      },
      quantity: Number
    }
  ]
});

我有一个疑问:

代码语言:javascript
复制
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,但发现操作符并不像我正在做的那样用于查询。

在此基础上:

代码语言:javascript
复制
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

对于我的查询,我想要类似于这个操作符的功能。

,让我们打破我的条件:

对于我的布尔表达式:我想检查req.body.itemID对于我的购物车中的任何值是否是$ne

如果是这样的话:将$push itemID和quantity放到购物车中

Else (然后项已经存在):$inc的数量为1

问题:如何实现这一结果?我需要分开两次查询吗?如果可能的话,我尽量避免那样做

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-23 22:00:50

我查看了他们所有的更新字段操作符,而且可能没有办法以我想要的方式完成这个任务。

我想知道为什么没有用于更新操作符的$cond。尽管如此,我还是有了我想要的功能实现的解决方案。只是不像我喜欢的那样优雅。

代码语言:javascript
复制
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();
        }
});
票数 1
EN

Stack Overflow用户

发布于 2018-03-23 18:42:09

这种类型的逻辑不属于数据库查询。它应该发生在应用层。MongoDB在检索和更新单个记录时使用索引也非常快,因此这不应该引起关注。

请试着做这样的事情:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49449179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档