Mongo填充在可选字段中,导致投放错误

我有一个“供应商”和“媒体”集合,媒体集合存储了供应商资料图像,这对于供应商来说不是必填字段。有些供应商提供个人资料图片,有些则没有,我想列出所有供应商,包括他们的个人资料图片参考。但是,当我从meidas填充profilePicture时,出现了投射错误。我还有其他填充,例如“ userId”,“ venueId”,它们是必填字段,并且可以工作。

错误: CastError:对于未定义的模型“媒体”,在路径“ _id”的值“ xyz”的Cast失败,投射到ObjectId

查找查询:

const result = await resultObject.skip(skip)
    .populate('userId')
    .populate('venueId')
    .populate('profilePicture')
      .limit(parseInt(obj.pageSize,10))
      .sort({ [obj.sortColumn]: parseInt(obj.sortvalue,10) });
    return result;

媒体模型

const MediasModel = () => {
  const MediasSchema = new mongoose.Schema({
    url: { type: String,required: true },key: { type: String},},{ timestamps: { createdAt: 'createdDate',updatedAt: 'modifedDate' } });
  return mongoose.model('medias',MediasSchema);
};

module.exports = MediasModel();

供应商模型

const Vendors = new mongoose.Schema({
  venueId: { type: mongoose.Schema.Types.ObjectId,ref: 'venues' },userId: { type: mongoose.Schema.Types.ObjectId,ref: 'users' },name: { type: String,profilePicture: { type: mongoose.Schema.Types.ObjectId,ref: 'medias' },updatedAt: 'modifedDate' } });

module.exports = mongoose.model('vendors',Vendors);
xkcxkcxkc 回答:Mongo填充在可选字段中,导致投放错误

尝试以下代码

const Vendors = require('path/to/model_vendor');

Vendors.find()
.populate([{path: 'venues'},{path: 'users'},{path: 'medias'}])
.skip(skip_value)
.limit(limit_value)
.sort({condition: 1 }) // Modify according to your need
.exec().
.then(vendors=>{
console.log(vendors)
}).catch(err=>{
console.log(err)
})
本文链接:https://www.f2er.com/3069378.html

大家都在问