【发布时间】:2020-11-21 06:11:09
【问题描述】:
我知道以前有人问过这个问题,但经过数小时的研究,我尝试了几种方法来解决我的问题,但都没有成功。
架构
const ValuationsSchema = new Schema(
{
value: { type: Number, required: true, min: 0, max: 5 },
author: {
type: Schema.Types.ObjectId,
refPath: "fromModel",
required: true,
},
fromModel: {
type: String,
required: true,
enum: ["usertype1", "usertype2", "usertype3"],
trim: true,
},
},
{
timestamps: true,
}
);
const UserSchema = new Schema(
{
name: { type: String, required: true, trim: true },
valuations: [ValuationsSchema],
},
{
timestamps: true,
}
);
我想做什么
我正在尝试在user 的valuations 数组中填充ValuationsSchema 的author 字段。
样本数据
预期结果
{
_id: 5f1ef9f6039fea10c437939c,
name: 'Jose Maria',
createdAt: 2020-07-27T15:59:50.529Z,
updatedAt: 2020-08-01T15:34:47.414Z,
valuations: [
{
_id: 5f258b973c0ac544869c0434,
value: 5,
author: Object,
fromModel: 'particular',
createdAt: 2020-08-01T15:34:47.414Z,
updatedAt: 2020-08-01T15:34:47.414Z
}
]
}
得到结果
{
_id: 5f1ef9f6039fea10c437939c,
name: 'Jose Maria',
createdAt: 2020-07-27T15:59:50.529Z,
updatedAt: 2020-08-01T15:34:47.414Z,
valuations: [
{
_id: 5f258b973c0ac544869c0434,
value: 5,
author: 5f1edaa83ce7cf44a2bd8a9a,
fromModel: 'particular',
createdAt: 2020-08-01T15:34:47.414Z,
updatedAt: 2020-08-01T15:34:47.414Z
}
]
}
已经尝试过的解决方案
目前我手动填充了该字段,但由于这是一种很好的做法,我正在尝试尽可能使用 API。
就我而言,执行此操作应该可以完成工作,但事实并非如此。
await user.populate("valuations.author").execPopulate();
也没有运气尝试过:
await user.populate({
path: "valuations",
populate: {
path: "author",
},
}).execPopulate();
也尝试了deepPopulate package,但结果相同。
【问题讨论】:
-
@turivishal 添加了示例数据!如果您需要任何其他信息,请告诉我。
-
@turivishal 我希望用户文档与存储在该字段中的对象 ID 相关联。
-
@turivishal 我试过了,我得到了这个错误
Schema hasn't been registered for model \"fromModel\".\nUse mongoose.model(name, schema)我需要使用 refPath,因为它是我定义的 3 个可能的用户模型的dynamic reference["usertype1", "usertype2", "usertype3"],
标签: node.js mongodb mongoose mongoose-populate