【问题标题】:Mongoose populated() returns undefined despite the path being populated尽管路径被填充,猫鼬填充()返回未定义
【发布时间】:2021-04-15 17:05:51
【问题描述】:

我有以下 Mongoose 架构:

// server/models/Order.js

const { connection, model, Schema } = require('mongoose');

const itemSchema = new Schema({
    product: { type: Schema.Types.ObjectId, ref: 'Product', required: true },
    quantity: { type: Number, required: true },
    purchasePrice: {
        type: Schema.Types.Decimal128, get: Number, required: true, validate: {
            validator: function (value) {
                return !this.populated('product') || +value === this.product.price;
            },
        }
    },
});

const schema = new Schema({
    // ...
    items: [itemSchema],
    // ...
});

module.exports = model('Order', schema);

我的服务器创建一个新订单,填充它,然后尝试保存它:

// server/routers/order.js

const Order = require('../models/Order');

const order = new Order({ ... });
await order.populate('items.product').execPopulate();
const { _id } = await order.save();

调用验证函数。调试器显示this.product 引用了一个有效的文档,而this.populated('product') 返回undefined,因此不评估比较+value === this.product.price。

这是 Mongoose 中的一个错误,还是出于某种原因它的行为方式?

【问题讨论】:

    标签: node.js mongodb validation mongoose mongoose-populate


    【解决方案1】:

    是的,我认为这是一个错误。 我也发现了这个。

    const trackSchema=new Schema({
      song:{
        type:Schema.Types.ObjectId,
        ref:"Attachments",
       index:true
      },
      played:{
       type:Number,
       default:0
      }
    });
    const playlistSchema=const plSchema=new Schema({
      name:String,
      tracks:[trackSchema]
    });
    

    填充前:

    playlist.tracks.forEach((track)=>{
       console.log('track.song: ',track.song);
       //this prints ObjectId
    });
    

    填充后:

    await playlist.populate('tracks.song').execPopulate();
    playlist.tracks.forEach((track)=>{
       console.log('track.song: ',track.song);
       //this prints undefined
    });
    

    修改为:

    await playlist.populate('tracks').execPopulate();
    playlist.tracks.forEach((track)=>{
       console.log('track.song: ',track.song);
       //this prints undefined
    });
    

    仍未定义?‍♂️

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2015-07-13
      • 2016-10-10
      相关资源
      最近更新 更多