Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor function in Mongoose schema/models

I am new to Node.js, mongodb and mongoose. I want to pass some parameter in creating a new document. For example, that is the typical example of creating a new document:

var animalSchema = new Schema({ name: String, type: String });
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({ type: 'dog' });

And I want do something like this:

var dog = new Animal( Array );

So I want to create custom constructor for a new document. But I dont know where and how I can set a custom constructor like that in mongoose.

I have a stackoverflow post with a similar name but it seems not be something that I want: Custom constructor function in Mongoose schema/models

Maybe I make a silly mistake. Welcome to any ideas.

Thanks

like image 457
LKS Avatar asked Mar 05 '13 02:03

LKS


1 Answers

Mongoose doesn't support this kind of magic. But there're a few workaround that could solve this.

Define a static function:

In your schema definition, you can define a static function to deal with the instantiation of all models based on the objects of your array, like:

var animalSchema = new Schema({ name: String, type: String });
animalSchema.static({
  createCollection: function (arr, callback) {
    var colection = [];

    arr.forEach(function (item) {
       // Here you have to instantiate your models and push them
       // into the collections array. You have to decide what you're
       // going to do when an error happens in the middle of the loop.
    });

    callback(null, collection);
  }
});

Use Model.create method:

If you don't really need to manipulate your model instances before saving them, and you just want to instantiate and persist to the db, you can use Model.create, which accepts an array of objects:

var animals = [
  { type: 'dog' },
  { type: 'cat' }
];
Animal.create(arr, function (error, dog, cat) {
  // the dog and cat were already inserted into the db
  // if no error happened
});

But, if you have a big array, the callback will receive a lot of arguments. In this case, you could try to 'generalize':

Animal.create(arr, function () {
  // the error, if it happens, is the first
  if (arguments[0]) throw arguments[0];
  // then, the rest of the arguments is populated with your docs
});

Use Model.collection.insert:

Like explained in the docs, it's just an abstract method that must be implemented by the driver, so it doesn't have any mongoose treatment and it could add unexpected fields to your collection. At least, if you pass an array of objects, it will persist them and return an array with the populated method:

var animals = [
  { type: 'dog' },
  { type: 'cat' }
];
Animal.collection.insert(animals, function (error, docs) {
   console.log(docs);
});
like image 186
Rodrigo Medeiros Avatar answered Nov 05 '22 07:11

Rodrigo Medeiros