7

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.

2 Answers 2

7

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) {...});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank, you save me. My mistake is I use $addToSet, but I push a single item to array, and it don't allow. Then I create an array and use $ set. Hooray, it work properly.
-3
db.t1.insert({name:"sachin"})
db.t1.insert({name:"shukla"})
db.t1.update({}, {$set:{arr:[]}}, {multi:true} )
db.t1.update({}, {$push: {arr:"tmp"} }, {multi:true} )

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.