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?
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.
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.
and it will return array? find returns an array always.
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.
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) {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With