Skip to content Skip to sidebar Skip to footer

Mongo $addtoset With Multiple Values Correct Syntax

I have this mongoose schema: var listingSchema = new Schema({ street : String, buildingNumber : Number, apartmentNumber : Number, UsersAnd

Solution 1:

You need to add object to set UsersAndQuestions:

{$addToSet: {UsersAndQuestions: { userID: idToAdd, questionID: questionToAdd } }}

UPDATE.

I would do it with two queries:

Listing.update({_id: ObjectId(listingToUpdate), 'UsersAndQuestions.userID': idToAdd}, 
    {"$addToSet": {"UsersAndQuestions.$.questionID": questionToAdd}}
    , function (err, result) {
        if(result.n === 0){
            //we haven't found document with the userId - idToAdd//we need to insert to UsersAndQuestions document with this user
            Listing.update({_id: ObjectId(listingToUpdate)},
                {$addToSet: {UsersAndQuestions: { userID: idToAdd, questionID: questionToAdd } }}, 
                function(err, res){

                })
        }
})

Post a Comment for "Mongo $addtoset With Multiple Values Correct Syntax"