For example, I have a collection, such as User
, with one field name
(and default _id
field). I insert some documents to this collection.
Then I want to add a field emails
(which is an array to insert multiple emails) to this collection. If it is a normal field (not is an array), it can do easy with update
and $set. But, with the array, I cannot create a new field with update
command and $upsert, $addToSet, $push... because the array has not created before.
I think this is a common behavior, but I cannot find any way to do that.
All of the $set
, $addToSet
, and $push
operators will create the array if the field doesn't exist yet. Make sure you've added email
to your Mongoose model's schema for the update
to properly occur.
var userSchema = new Schema({
name: String,
emails: [String]
});
All three of the below options would have the same effect of adding the array of emails if the emails
field doesn't exist yet or is empty:
var emails = ['[email protected]', '[email protected]'];
User.update({_id: id}, {$set: {emails: emails}}, function(err, num) {...});
User.update({_id: id}, {$addToSet: {emails: {$each: emails}}}, function(err, num) {...});
User.update({_id: id}, {$push: {emails: {$each: emails}}}, function(err, num) {...});
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