Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push value to Array if key does not exist Mongoose [duplicate]

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?

like image 544
Glen Swift Avatar asked Oct 12 '14 19:10

Glen Swift


People also ask

Can I use $in in Mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.

What is $Push in Mongoose?

The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

Does find return an array Mongoose?

and it will return array? find returns an array always.

What is the difference between schema and model in Mongoose?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


1 Answers

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) {
    ...
});
like image 61
Gergo Erdosi Avatar answered Sep 19 '22 14:09

Gergo Erdosi