【问题标题】:Mongoose populate virtuals producing 'undefined'Mongoose 填充虚拟对象,产生“未定义”
【发布时间】:2021-07-01 14:14:01
【问题描述】:

我之前在其他 Schema 上创建了 Mongoose virtuals 并没有问题,但我现在有一个不会填充,并且不确定该怎么做。

        const InventorySchema = new mongoose.Schema(
      {
        name: { type: String }, 
        ............
    
      },
      {
        toJSON: { virtuals: true },
        toObject: { virtuals: true },
      }
    );
    
    InventorySchema.virtual('logs', {
      ref: 'Log',
      localField: '_id',
      foreignField: 'inventory',
    });


module.exports = mongoose.model('Inventory', InventorySchema);

这是它所引用的日志架构。

const LogSchema = new mongoose.Schema(
  {
    ...other info,
    inventory: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Inventory',
    },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

module.exports = mongoose.model('Log', LogSchema);

尽管存在记录,但调用inventory.find 会导致未定义

const inventory = await Inventory.findById(req.params.id).populate('logs');
console.log(inventory.populated('logs'));      //undefined
console.log(inventory.logs);                   //undefined


const invLogs = await Log.find({ inventory: inventory._id });
console.log('invLogs: ', invLogs.length);      // 5 - so the records exist

我在这里搜索过,但没有找到适合我的答案。我认为我做错了什么,但我在其他收藏中有类似的虚拟。我应该提一下,我在 Inventory 上使用了 mongoose-autopopulate,我还没有看到它和 virtuals 有任何问题,但我可能是错的。

【问题讨论】:

    标签: mongodb mongoose virtual populate


    【解决方案1】:

    根据mongoose documentation,virtuals 的语法如下:

    const userSchema = mongoose.Schema({
      email: String
    });
    // Create a virtual property `domain` that's computed from `email`.
    userSchema.virtual('domain').get(function() {
      return this.email.slice(this.email.indexOf('@') + 1);
    });
    const User = mongoose.model('User', userSchema);
    
    let doc = await User.create({ email: 'test@gmail.com' });
    // `domain` is now a property on User documents.
    doc.domain; // 'gmail.com'
    

    具体来说,注意对get()的调用,参数是返回所需值的函数。

    【讨论】:

    • 谢谢,但是 mongoose populate-virtual 给出了这个例子:link。它使用一个对象作为 virtual 的第二个参数来引用另一个集合。 BandSchema.virtual("members", { ref: "Person", localField: "name", foreignField: "band", justOne: false, });
    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 2018-05-20
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2017-09-19
    • 2018-10-20
    相关资源
    最近更新 更多