【问题标题】:Mongo populate in optional field giving cast errorMongo 在可选字段中填充给出转换错误
【发布时间】:2020-03-15 15:02:30
【问题描述】:

我有一个“供应商”和“媒体”收藏,媒体收藏商店供应商个人资料图片,这不是供应商的必填字段。有些供应商有资料图片有些没有,我想列出所有供应商,包括他们的资料图片参考。但是当我从 meidas 填充 profilePicture 时,我遇到了投射错误。我还有其他填充,例如“userId”、“venueId”,它们是必填字段,并且可以正常工作。

错误: CastError:对于模型“medias”未定义的路径“_id”处的值“xyz”,转换为 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, required: true },
  profilePicture: { type: mongoose.Schema.Types.ObjectId, ref: 'medias' },
}, { timestamps: { createdAt: 'createdDate', updatedAt: 'modifedDate' } });

module.exports = mongoose.model('vendors', Vendors);

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    试试下面的代码

    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)
    })
    

    【讨论】:

    • 试过但没有得到任何填充结果,我的意思是现在用户,场所是笔记列表,得到所有没有填充字段的供应商
    • 它使用相同的填充查询,问题是数据库中有一些旧的垃圾数据。
    • @Dibish 是的,你是对的。正如您的错误提示,Cast to ObjectId failed for value "xyz" at path "_id" xyz cannot be objectid
    猜你喜欢
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多