第一篇文章在这里,所以大家好!
我在mongoose填充上遇到了麻烦,因为它显然什么也没做。我直接去代码。
以下是我的模型:
空格键
const spaceSchema = Schema(
{
user: {
type: Schema.Types.ObjectId,
required: true,
ref: "User",
},
name: {
type: String,
required: true,
},
days: [{ type: Schema.Types.ObjectId, refPath: "Day" }],
},
{
versionKey: false,
timestamps: true
},
);
const Space = mongoose.model("Space", spaceSchema);
module.exports = Space;
日
const daySchema = Schema(
{
space: { type: Schema.Types.ObjectId, refPath: "Space" },
date: {
type: String,
required: true,
},
water: {
type: Boolean,
},
fertilizer: {
type: Boolean,
},
transplant: {
type: Boolean,
},
comment: {
type: String,
},
},
{
versionKey: false,
timestamps: true
},
);
const Day = mongoose.model("Day", daySchema);
module.exports = Day;
在控制器的一部分中,我有getSpace路由(/api/spaces/:id):
const getSpace = asyncHandler(async (req, res) => {
const space = await Space.findById(req.params.id).populate("days");
res.status(200).json(space);
});
这是我得到的结果:
{
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": []
}
我试了很多方法,但结果都一样。
如果你还需要密码的其他部分,请告诉我。
谢谢大家:D
我希望结果看起来像这样
"space": {
"_id": "63580115978dbf8f2f5a7a50",
"user": "63501ab84613855834daa4ef",
"name": "spaceName",
"days": [
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": true,
"fertilizer": true,
"transplant": false,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
},
{
"_id": "63581af565aed8cad3210046",
"space": "63580115978dbf8f2f5a7a50",
"date": "29/10/2022",
"water": false,
"fertilizer": false,
"transplant": true,
"comment": "This is a comment.",
"createdAt": ...,
"updatedAt": ...
}
]
}
2条答案
按热度按时间50pmv0ei1#
使用ref而不是refPath
就像这样
vqlkdk9b2#
参考:https://mongoosejs.com/docs/populate.html