Additional Mongoose update document, if one exists

I have the following model:

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);

Suppose that is user1registered in the user, and question1- current / view question. The user can upvote({up: true}) or downvote({up: false}) ask a question at any time. How can I addcreate a new voteone if I have user1not voted for the question1else updatevote.

I managed 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);
        }
    });

});
+3
source share
1 answer

, , , , doc, doc . MongoDB , , , , .

, true false, .

, vote.value true false "upvote"

, , :

Question.update(
  { 
    _id: questionId, 
    "votes.createdBy" vote.createdBy,
    "votes.up": {"$ne": vote.value }
  },
  { $set: { "votes.$.up": vote.value } }
);

, positional $, , . , , , , vote.vaule .

$push new:

Question.update(
  { 
    _id: questionId
  },
  { 
    $push: { 
      "votes": {
        "up": vote.value,
        "createdBy": vote.createdBy
      }
    }
  }
);

, , writeConcern, , , .

+8

All Articles