Mongoose模式/模型中的构造函数

我是Node.js,mongodb和mongoose的新手。 我想传递一些参数来创build一个新的文档。 例如,这是创build新文档的典型示例:

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

我想要做这样的事情:

 var dog = new Animal( Array ); 

所以我想创build一个新的文档的自定义构造函数。 但是我不知道在哪里以及如何在mongoose中设置自定义的构造函数。

我有一个类似名称的stackoverflow后,但它似乎不是我想要的东西: 在Mongoose架构/模型中的自定义构造函数

也许我犯了一个愚蠢的错误。 欢迎来到任何想法。

谢谢

mongoose不支持这种魔法。 但有几个解决方法可以解决这个问题。

定义一个静态函数:

在您的模式定义中,您可以定义一个静态函数来处理基于数组对象的所有模型的实例,如:

 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); } }); 

使用Model.create方法:

如果您在保存模型实例之前不需要操作模型实例,并且只想实例化并保存到数据库,则可以使用Model.create ,它接受一组对象:

 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 }); 

但是,如果你有一个大数组,callback会收到很多的参数。 在这种情况下,你可以尝试“概括”:

 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 }); 

使用Model.collection.insert

就像在文档中解释的那样,这只是一个必须由驱动程序实现的抽象方法,所以它没有任何mongoose的处理,并且可能会为您的collections添加意想不到的字段。 至less,如果你传递一个对象数组,它将会持久化它们,并返回一个包含了方法的数组:

 var animals = [ { type: 'dog' }, { type: 'cat' } ]; Animal.collection.insert(animals, function (error, docs) { console.log(docs); });