【问题标题】:Mongoose middleware access other collectionMongoose 中间件访问其他集合
【发布时间】:2014-10-28 23:03:05
【问题描述】:

我正在使用“pre”“保​​存”中间件为“用户”文档创建相应的“用户对象”文档。

所以有users 集合和userObjects。 当插入新的user 时,也应该插入一个userObjects 文档。

我正在尝试使用“pre”中间件,就像这样:

//before inserting a new user
Users.pre('save', function(next) {
    var UserObjects = db.model('userObjects');

    userObjectsIns = new UserObjects({
         'userID': this._id,
         'myObjects':[],
    });

    userObjectsIns.save( function(err) {
        if (err) console.log("ERROR while saving userObjectsIns: " + err);
        next()
    })        
});

明显的问题是db 不存在。如何从这个 pre 中间件中访问“userObjects”集合?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以通过this doc 实例的model 方法访问其他模型:

    Users.pre('save', function(next) {
        var UserObjects = this.model('userObjects');
    
        userObjectsIns = new UserObjects({
             'userID': this._id,
             'myObjects':[],
        });
    
        userObjectsIns.save( function(err) {
            if (err) console.log("ERROR while saving userObjectsIns: " + err);
            next()
        })        
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2014-08-25
      • 2014-02-04
      • 2018-06-11
      • 1970-01-01
      • 2016-02-20
      • 2020-11-16
      • 1970-01-01
      • 2016-04-12
      相关资源
      最近更新 更多