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

LKS*_*LKS 9 mongoose node.js

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

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

我想做这样的事情:

var dog = new Animal( Array );
Run Code Online (Sandbox Code Playgroud)

所以我想为新文档创建自定义构造函数.但我不知道在mongoose中我可以在哪里以及如何设置这样的自定义构造函数.

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

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

谢谢

Rod*_*ros 3

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);
  }
});
Run Code Online (Sandbox Code Playgroud)

使用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
});
Run Code Online (Sandbox Code Playgroud)

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

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
});
Run Code Online (Sandbox Code Playgroud)

使用Model.collection.insert

正如文档中所解释的,它只是一个必须由驱动程序实现的抽象方法,因此它没有任何猫鼬处理,并且可能会向您的集合添加意外的字段。至少,如果您传递一个对象数组,它将保留它们并使用填充方法返回一个数组:

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