gpt4 book ai didi

javascript - Mongo 填充可选字段,给出强制转换错误

转载 作者:行者123 更新时间:2023-12-02 22:29:57 25 4
gpt4 key购买 nike

我有一个“vendor ”和“媒体”集合,媒体集合存储 vendor 配置文件图像,这不是 vendor 的必填字段。有些 vendor 有个人资料图片,有些没有,我想列出所有 vendor ,包括他们的个人资料图片引用。但是当我从 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();

vendor 模型

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

最佳答案

尝试下面的代码

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

关于javascript - Mongo 填充可选字段,给出强制转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com