13

Given mongoose schema

var SomeSchema = new Schema({
    // ...
    members: [
        {
            name: String,
            username: String
        }
    ]
});

From my code I want to push object to members but only if there is no given username in array yet. How can I do it with mongoose?

Community
  • 1
  • 1
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79
  • you can find by query like db.collection.find({'member.username':username}) if the collection is empty then push object into the member array – Muhammad Ali Oct 12 '14 at 19:56

1 Answers1

65

You could check for the username in the condition part of the update query:

var conditions = {
    _id: id,
    'members.username': { $ne: 'something' }
};

var update = {
    $addToSet: { members: { name: 'something', username: 'something' } }
}

SomeModel.findOneAndUpdate(conditions, update, function(err, doc) {
    ...
});
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • Thanks! I've run into the same problem. I would like to point out that if you want to return an error message if a member with the `username` already exists you should check `doc === null` on the object returned by `findOneAndUpdate` . – Akos K Jul 19 '15 at 11:59