猫鼬更新子文档(如果存在) [英] Mongoose update sub document if exists
问题描述
我有以下模型:
var VoteSchema = new Schema({
up : Boolean
, createdBy:{type:ObjectId, ref:'users'}
, createdOn : {type:Date, default:Date.now}
});
var QuestionSchema = newSchema({
title:String
, description:String
, votes : [VoteSchema]
, createdBy:{type:ObjectId, ref:'users'}
, createdOn : {type:Date, default:Date.now}
});
var Question = mongoose.model('questions',QuestionSchema);
假设user1
已登录用户并且question1
是当前/查看问题.用户可以随时upvote
({up:true})或downvote
({up:false})一个问题. 如果user1
尚未对question1
进行投票,否则update
投票,我如何add
新的vote
.
Suppose user1
is logged in user and question1
is current / viewing question.The user can upvote
({up:true}) or downvote
({up:false}) a question at any time. How can I add
a new vote
if a user1
have not casted a vote for question1
else update
the vote.
我已经能够编写以下代码行:
I have been able to write the following lines of code:
QuestionSchema.statics.castVote = function(questionId, vote) {
//NOTE : vote.createdBy equalsto loggedInUserID
Q.nbind(Question.findOne, Question)({
$and:[
{_id:questionId},
{'votes.createdBy':vote.createdBy}
]
}).then(function(doc) {
if(doc) {
//I am clue less
//doc.votes is a list of votes for this question
// how can I get the particular vote casted by the user - vote.createdBy
}else {
//Question.votes.push(vote);
}
});
});
推荐答案
所以您是其中的一部分,但是当然,当您找不到doc
时,就不会有doc
了.在回调中使用. MongoDB具有处理此类更新的本机方式,但是您当然需要按原样测试匹配.
So you're part of the way there, but of course when you don't find a doc
then you will not have a doc
to work with in the callback. MongoDB has native ways of handling these sorts of updates, but of course you do need to test for the match as you are.
我们在这里可以做的只是在文档存在的true
或false
条件下工作.
What we can do here is just work within the true
or false
condition of where the document exists.
考虑将vote.value
用作"upvote"的true
或false
Considering vote.value
to be your true
or false
for the "upvote"
在发现有匹配文档的地方,可以发出如下更新:
Where you do find that there is a matching document you can issue an update like this:
Question.update(
{
_id: questionId,
"votes.createdBy" vote.createdBy,
"votes.up": {"$ne": vote.value }
},
{ $set: { "votes.$.up": vote.value } }
);
因此可以匹配并使用位置 $
运算符以确保匹配项的正确 index 已更新.我在此处添加的内容可以确保即使在vote.vaule
已经具有相同值的文档上,您也不要碰它.
So that matches and uses a positional $
operator to make sure the correct index of the matching item is updated. What I added there makes sure that you don't even touch the document where the vote.vaule
is already of the same value.
在错误的条件下,您想要 $ push 到带有 new 项的数组:
And in the false condition you want to $push onto the array with the new item:
Question.update(
{
_id: questionId
},
{
$push: {
"votes": {
"up": vote.value,
"createdBy": vote.createdBy
}
}
}
);
当然可以在应用writeConcern
的地方添加回调详细信息.
Of course add the callback details where writeConcern
is applied, which you probably do.
这篇关于猫鼬更新子文档(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!