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

9

我是一个新手,对Node.js、mongodb和mongoose不太熟悉。我想在创建新文档时传递一些参数。例如,以下是创建新文档的典型示例:

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

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

我在stackoverflow上发布了一个类似的帖子,但它似乎不是我想要的:Mongoose模式/模型中的自定义构造函数

也许我犯了一个傻瓜错误。欢迎任何想法。

谢谢


我认为你可以使用预初始化或后初始化钩子,如此处所述(http://mongoosejs.com/docs/middleware.html),但我自己无法使其工作。 - Benoir
@Benoir - 刚刚尝试了同样的事情。我认为“init”回调仅在从数据库加载时触发,而不是对象构建时触发。 - bimsapi
将它包装在另一个构造函数中? - ambrosechua
你是想让 var dogs = new Animal( Array ); 返回一个文档数组,还是询问如何将由自定义构造函数创建的动物模式中的 nametype 属性设置为包含 2 个字符串的数组? - Brian Shamblen
1个回答

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

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

但是,如果您有一个大的数组,回调函数将会接收到很多参数。在这种情况下,您可以尝试“泛化”:

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处理,并且可能会向您的集合添加意外的字段。至少,如果您传递对象数组,它将持久化它们并返回一个带有填充方法的数组:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接