Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new array field to collection in mongodb?

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.

like image 480
t4nhpt Avatar asked Jun 21 '15 01:06

t4nhpt


1 Answers

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) {...});
like image 64
JohnnyHK Avatar answered Sep 21 '22 00:09

JohnnyHK