Mongoose plugin for document merging
var merge = require('mongoose-merge-plugin');
var mongoose = require('mongoose'); mongoose.plugin(merge);
The method merge is added to all mongoose documents. It takes a source object as paramter and merge it in the target existing documents. It checks for existing values in the source object regarding the field path of the destination document. It does not merge the _id and __v default fields and check for the schema field option mergeable, if the option is false, the merge skip the field as well.
var mongoose = require('mongoose'), Schema = mongoose.Schema; var schema = new Schema({ name: String, notMergedField: { type: String, mergeable: false } }); var model = mongoos.model('Test', schema); var test = new Test({name: test, notMergedField: testNMF }); console.log(test); // LOG: { i_id: ..., name: test, notMergedField: testNMF ...} test.merge({ name: testChanged, notMergedField: testNMFChanged }); console.log(test); // LOG: { i_id: ..., name: testChanged, notMergedField: testNMF ...}