我正在构建架构(Meal),我希望此架构中的字段之一(meat_name)取自不同架构(Meat)的不同字段(meatName)。 我知道填充方法,但它引用整个集合,我想引用特定字段。
-Meat Schema-
const meatSchema= new Schema({
MeatName: String,
MeatDescription: String,
});
module.exports = mongoose.model("Meat", meatSchema);
-Meal Schema-
const mealSchema= new Schema({
mealName: String,
mealPrice: Number,
meat_name: {
type: Schema.Types.ObjectId,
ref: "Meat" /*populate method return the entire collection, but I want just the meatName field in that collection */,
},
});
module.exports = mongoose.model("Meal", mealSchema);
我认为,您可以通过使用
virtual
来实现这一点(在此处了解更多信息 https://mongoosejs.com/docs/tutorials/virtuals.html)
根据你的问题-
mealSchema.virtual('meat_name', {
ref: 'Meat', // ref model to use
localField: 'meat_name', // field in mealSchema
foreignField: 'MeatName', // The field in meatSchema.
});
MeatName
中的 meatSchema
可以是任何东西。
您可以使用 SELECT 选项指定要填充的特定字段 https://mongoosejs.com/docs/populate.html#populate-multiple-paths
对于你的问题:
await mealSchemafind().populate({ path: 'meat_name', select: '_id MeatName' })