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
Mongoose doesn't support this kind of magic. But there're a few workaround that could solve this.
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);
}
});
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
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With