14

问候大家!

我如下定义了一个 Mongoose 模式并注册了一个模型(InventoryItemModel)。有没有办法为模式创建自定义构造函数,这样当我从模型中实例化一个对象时,该函数将被调用(例如,从数据库中加载具有值的对象)?

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var InventoryItemSchema = new Schema({
    Sku : String
  , Quanity : Number
  , Description : String
  , Carted : []
  , CreatedDate  : {type : Date, default : Date.now}
  , ModifiedDate  : {type : Date, default : Date.now}
});

mongoose.model('InventoryItem', InventoryItemSchema);

var item = new InventoryItem();

我可以添加一些自定义构造函数,以便在实例化时从数据库中填充项目吗?

4

5 回答 5

14

根据您要采取的方向,您可以:

1)使用钩子

当模型初始化、验证、保存和删除时,钩子会自动触发。这是“由内而外”的解决方案。您可以在此处查看文档:

2)为您的模式编写一个静态创建函数。

静力学存在于您的模型对象上,可用于替换创建新模型等功能。如果您的create步骤有额外的逻辑,您可以自己在静态函数中编写。这是“由外而内”的解决方案:

于 2013-01-09T05:57:46.570 回答
6

这是来自答案的选项#2 的@hunterloftis实现。

2)为您的模式编写一个静态创建函数。

someSchema.statics.addItem = function addItem(item, callback){
//Do stuff (parse item)
 (new this(parsedItem)).save(callback);
}

当您想从 someSchema 创建新模型时,而不是

var item = new ItemModel(itemObj);
item.save(function (err, model) { /* etc */ });

做这个

ItemModel.addItem(itemObj, function (err, model) { /* etc */ });
于 2014-08-22T19:57:59.960 回答
2

我自己遇到了这个问题并写了一个猫鼬插件来帮助解决你的问题

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , construct = require('mongoose-construct')

var user = new Schema({})
user.plugin(construct)

user.pre('construct', function(next){
    console.log('Constructor called...')
    next()
})

var User = mongoose.model('User', user)
var myUser = new User(); // construct hook will be called

这是 repo(也可以在 npm 上找到):https ://github.com/IlskenLabs/mongoose-construct

于 2013-06-04T17:30:09.203 回答
0

@hunterloftis provided me the answer I needed. Now, nearly 6+ years later, here is my solution for anyone else.

InventoryItemSchema.static( 'new', function( that )
{
    let instance = new InventoryItemSchema();
    Object.assign( instance, that );
    return instance;
});

or as the one-liner (which is less conducive to debugging)

InventoryItemSchema.static( 'new', function( that )
{return Object.assign( new InventoryItemSchema(), that );});

Either way, where you would like to have

let inventoryItem = new InventoryItemSchema({...});

you will instead have

let inventoryItem = InventoryItemSchema.new({...});
于 2019-11-09T00:13:17.330 回答
-5

你需要导出。这是一个例子:

import mongoose from "mongoose";

let  Schema = mongoose.Schema;


let restaurentSchema = new Schema({
  name : String
})

//export

module.exports = mongoose.model("Restaurent", restaurentSchema)
于 2016-12-11T20:46:02.163 回答