【问题标题】:Mongoose population in instance methods实例方法中的猫鼬种群
【发布时间】:2015-09-01 07:44:27
【问题描述】:

我有一个参考其他文档的模型。我想在该模型中有一个方法可以处理引用模型中使用的数据。

'use strict';

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
    , deepPopulate = require('mongoose-deep-populate');

var MainSchema = new Schema({
  childs: [{type:Schema.ObjectId, ref: 'Child'}], //because many-to-one
  startDate: {type: Date, default: Date.now},
  endDate: {type: Date},
});


MainSchema.methods = {

  retrieveChilds: function(callback) {

    // deepPopulation of childs not possible??

    callback(result);
  },
};

MainSchema.plugin(deepPopulate);

module.exports = mongoose.model('Main', MainSchema);

如上面的代码示例所示,retrieveChilds 函数应在当前 Schema 上执行 deepPopulate 函数。这是可能的还是应该在模型之外发生? (这有时会导致重复代码)

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    在 Mongoose instance methods 中,this 是正在调用该方法的文档实例,因此您可以这样做:

    MainSchema.methods = {
      retrieveChilds: function(callback) {
        this.deepPopulate('childs.subject.data', callback);
      },
    };
    

    然后调用它:

    main.retrieveChilds(function(err, _main) {
        // _main is the same doc instance as main and is populated.
    });
    

    【讨论】:

    • 谢谢,我之前试过这个,但当时没有用,显然我忘记了回调有 2 个参数,错误和返回对象。谢谢!
    猜你喜欢
    • 2016-07-31
    • 2019-09-13
    • 2017-06-02
    • 1970-01-01
    • 2016-07-11
    • 2016-11-24
    • 2018-02-10
    • 2013-11-27
    • 2016-12-17
    相关资源
    最近更新 更多