Teach Me Cool Stuff
Appending to child collection in MongoDB
In the following post I will show how to append documents to an existing array of sub documents using Mongoose and MongoDB.
Mongoose lets you define mongo documents with sub documents, but it also offers a great shortcut to appending to the child collection.
Assume the following schema consisting of a language schema with belonging translations in a child collection.
var translation = {
key:{type: String,required: true },
text:{type: String},
createdDate:{type: Date, default: Date.now}
};
var languageSchema = new mongoose.Schema({
code:{type:String, required: true},
name:{type:String, required: true},
isDefault:{type:Boolean, default:false},
translations:[translation]
},{ versionKey: false });
It turns out that Mongoose provides a handy short cut for appending to the translations in a single update statement. The statement below will append the same set of translations to the translations collection of all language documents. However, you can also add a filter if you want to limit the set of language documents to update.
var translations = [...] //translations to add
languageModel.update({},
{ $push: { translations: { $each: translations } } },
{ multi: true }).exec();
The key to this are the $push and $each operators.