Node.js – Saving Mongoose object into two collections

mongodbmongoosenode.js

Currently I have a node application which uses mongoose to save an object into a MongoDB. I am using a model similar to this:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var RegistrationSchema = new Schema({
        name:{ type: String, default: '', trim: false}
});

mongoose.model('Registration', RegistrationSchema);

Which saves my objects into a collection called registrations.

I save my registrations as such:

var registration = new Registration(data);

      registration.save(function(err) {
        if (err) {
          return callback({
            source: 'data_save',
            type: 'admin',
            errors: err
          });
        }
        else {
          return callback(null, data);
        }
      });

I would also like to save this same object when I create it, into another collection with a different name, such as registrations_new, or something to that effect. I want to duplicate this entry into the new collection. I tried to add the other collection in the connection string, which broke the mongo part entirely, I tried to create a new model called New_Registration, load that Schema and try to save it individually, but I have another issue with that. It seems that Mongoose pairs the schema with the collection, and that there really is no way to overwrite which collection it is saving to.

Anyone have any solution for this?

Best Answer

You can use the same schema in multiple models, so something like this works:

var RegistrationSchema = new Schema({
    name:{ type: String, default: '', trim: false}
});

var Registration = mongoose.model('Registration', RegistrationSchema);
var New_Registration = mongoose.model('New_Registration', RegistrationSchema);

var registration = new Registration(data);
registration.save();

var new_registration = new New_Registration(data);
new_registration.save();
Related Topic