【发布时间】: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 语句不返回从查询中找到的子文档。 怎么了?
【问题讨论】: