Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Mongoose object into two collections

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?

like image 658
David Allen Avatar asked Feb 27 '13 14:02

David Allen


1 Answers

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();
like image 197
JohnnyHK Avatar answered Sep 23 '22 23:09

JohnnyHK