【问题标题】:mongoose findOneAndUpdate return matched subdocument猫鼬 findOneAndUpdate 返回匹配的子文档
【发布时间】:2016-04-08 00:15:45
【问题描述】:

我必须修改架构中的一个子文档。在这个子文档中,我存储了一个密钥,用于与其他文档保持关系。只有当第一个文档被修改时,第二个文档才会被修改。我尝试使用 findOneAndUpdate 来做到这一点。

User.findOneAndUpdate({
            _id: ReceivingId,
            "friendship": {
                "$elemMatch": {
                    "_id": FriendshipId
                    , "verse": 1
                    , "status": "pending"
                }
            }
        }, {
            "$set": {
                "friendship.$.status": "accepted",
                "friendship.$.began": util.moment().toDate()
            },
            "$unset": {"friendship.$.verse": ""}
        }, {"new": true})
        .select('friendship.$')
        .exec()
        .then(function Query(upReceiving) {

            if (!upReceiving)
                throw new Error({status: 304, message: "No friendship update"});

            var ApplicantId = upReceiving.friendship.friend;
            console.log("Sender ID", upReceiving);

            return User.findOneAndUpdate({          //Query
                _id: ApplicantId,
                "friendship": {
                    "$elemMatch": {
                        "friend": ReceivingId,
                        "status": "pending"
                    }
                }

            }, {                            //Update
                "$set": {
                    "friendship.$.status": "accepted",
                    "friendship.$.began": util.moment().toDate()
                }

            }, {"select": "friendship.$", "new": true}).exec();

        })
        .then(function Query(upApplicant) {

            if (!upApplicant)
                return res.status(304).json({message: "No friendship update"});

            res.json({message: "Friendship accepted", friendship: {sender: upApplicant._id, receiver: ReceivingId}});

        }, function Error(err) {

            var status = 500;

            if (undefined !== err.status)
                status = err.status;

            console.log(err);
            res.status(status).json(err);
        });

第一次更新工作,但带有 $ 运算符的 select 语句不返回从查询中找到的子文档。 怎么了?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我正在阅读您的代码,对此我有疑问,

    “upReceiving.friendship.friend”字段是否包含有效的 ObjectId?

    我问这个是因为我看到了这条线:

    var ApplicantId = upReceiving.friendship.friend;
    

    然后,您尝试使用 ObjectId 等字段查找文档

    User.findOneAndUpdate(
                _id: ApplicantId,..
    

    【讨论】:

    • 不,它不包含该值,因为 findOneAndUpdate 没有返回我通过查询找到的子文档。我会那样做。我会 findOneAndUpdate 将匹配和修改的子文档返回给我。
    猜你喜欢
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2022-01-22
    • 2021-05-08
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多