3

Using mongoose against mongodb 2.6 - another issue raised that sounds 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 item but instead its storing 4!

However, changing the query 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 query 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 something Im missing.

Thanks.

J

Community
  • 1
  • 1
user1859465
  • 883
  • 1
  • 11
  • 28
  • I tested both update queries. and both of them just added one item. – Disposer Dec 11 '14 at 19:34
  • Is this the exact code, or a sample showing the issue? If your objects are more complex than the example in the question, keep this in mind from the documentation. *MongoDB determines that the document is a duplicate if an existing document in the array matches the to-be-added document exactly; i.e. the existing document has the exact same fields and values and the fields are in the same order.* – Timothy Strimple Dec 11 '14 at 19:48
  • Only when the schema is like this invite_list: [{type: String, trim: true}], does it work as expected. Have I missed something? – user1859465 Dec 11 '14 at 19:53

1 Answers1

3

After reading this, it got me thinking;

Stop Mongoose from creating _id property for sub-document array items

Found a fix;

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

Community
  • 1
  • 1
user1859465
  • 883
  • 1
  • 11
  • 28