Rob Paddock
Rob Paddock

Reputation: 1003

Mongo $addToSet still inserting despite item in array existing

I am trying to insert a new array item into an array of objects using $addToSet as I don't want duplicates

    var location = {
    place : req.body.location.Place,
    postcode : req.body.location.Postcode
}
User.update({_id: req.body._id},
         {$addToSet: { 'locations' : location}}, function(err, data) { 

});

This inserts a record every time even if place and postcode exactly match.

Thanks

Upvotes: 0

Views: 869

Answers (2)

Rob Paddock
Rob Paddock

Reputation: 1003

Thanks for your help Salvador It seems as I'm using Mongoose it adds the _id, I needed to create a subDocument or new schema for the array and set the _id to false

locations : [new mongoose.Schema(
    { 
        place : String,
        postcode : String
    },
    { _id: false})
]

All working fine now

Upvotes: 1

Salvador Dali
Salvador Dali

Reputation: 222999

I think that your results are not the same (they might look the same, but have invisible characters). For example:

db.a.insert({_id : 1, locs: []});

And then no matter how many times do you addToSet objects to the array locs:

db.a.update({_id : 1},{$addToSet : {
   locs: {a : 1, b: 2}
}})

Only the first one will be added.

So take a look at what are you adding, then try to do a raw mongo shell attempt. If it does not work correctly, post it here. Otherwise look more precisely at the data your app is providing to mongo.

Upvotes: 1

Related Questions