Mongodb using addtoSet to ensure no duplicates

Using mongoose versus mongodb 2.6 is another raised question similar to mine;

https://github.com/LearnBoost/mongoose/issues/1677

I have this piece of code:

$addToSet: { 
  invite_list: { 
    $each : [ 
      { email: 'test@test.com' }, 
      { email: 'test@test.com' }, 
      { email: 'test@test.com' },
      { email: 'test@test.com' }] 
  }
}

      

which should only store one element, but instead it stores 4!

However, changing the request to this

$addToSet: {
  invite_list: { 
    $each : [
      'test@test.com', 
      'test@test.com', 
      'test@test.com', 
      'test@test.com' ]
  }
}

      

returns one item as expected.

Model schema field:

invite_list: [{email: {type: String, trim: true}}],

      

The request looks like this:

UserModel.findOneAndUpdate(
        {
            _id: req.params.id,
        },
        {
            $addToSet: {invite_list: { $each : [{ email: 'test@test.com' },
                { email: 'test@test.com' },
                { email: 'test@test.com' },
                { email: 'test@test.com' }] }}
        }, function (err, user) {
            // morel logic here...        
            return res.status(200).json(user);
        });

      

http://docs.mongodb.org/manual/reference/operator/update/addToSet/

Is there anything that is missing.

Thank.

J

+3


source to share


1 answer


After reading this, I thought:

Stop Mongoose from creating _id property on subdocument array elements

Found a fix;

The model now looks like this:



 var subSchema = new mongoose.Schema({email: {type: String, trim: true, _id: false}},{ _id : false })

invite_list: [subSchema], 

      

Works as expected ...

J

+3


source







All Articles