【问题标题】:Mongo / Mongoose - Push object into document property array on conditionMongo / Mongoose - 根据条件将对象推送到文档属性数组中
【发布时间】:2021-01-10 14:13:28
【问题描述】:

我有一个存储在 mongo 上的文档,其中包含一个数组的属性类型,里面有一堆对象。我正在尝试将对象推送到该数组。然而,被推入数组的每个对象都包含一个日期对象。我需要它工作的方式是,如果具有该日期的对象已经存在,则不要将新对象推送到数组中。

我一直在玩它,尝试运行更新和 elemMatch 查询等,但我无法弄清楚。我在下面有一个很长的提取版本,如您所见,我正在向数据库发出 2 个单独的请求,有人可以帮我将其简化为更简单的吗?

 UserModel.findById(req.user._id, (err, doc) => {
        if (err) {
            return res.sendStatus(401);
        }
        const dateExists = doc.entries.find((entry) => entry.date === date);
        if (dateExists) {
            res.sendStatus(401);
        } else {
            UserModel.findByIdAndUpdate(
                req.user._id,
                {
                    $push: {
                        entries: {
                            date,
                            memo,
                        },
                    },
                },
                { safe: true, upsert: true, new: true },
                (err, doc) => (err ? res.sendStatus(401) : res.sendStatus(200))
            );
        }
    });

谢谢。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:
    db.users.updateOne({
      _id: req.user._id,
      "entries.date": date,
    },
    {
        $push: {
             entries: {date,memo},
        }
    })
    

    https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/index.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-08
      • 2019-04-08
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2019-09-18
      • 2020-04-02
      相关资源
      最近更新 更多