gpt4 book ai didi

javascript - Mongoose 复杂种群

转载 作者:行者123 更新时间:2023-12-03 00:29:00 24 4
gpt4 key购买 nike

我确实找到了 id 的帖子,并且我做了控制台日志输出,结果是:

{ comments: [ 5c263bf01b764a11c479f69c, 5c263c41133ace1655edee76 ],
_id: 5c263bc61b764a11c479f69b,
title: 'good laptop',
category: 'Laptop',
brand: 'dell',
Condition: 'Good Condition',
image: 'https://avisassets.abgemea.com/.imaging/flexibleIntroLarge/dms/DMS/local/ZA/fleet/fleet-page/luxury-cars-feature.jpg',
price: 2000,
priceState: 'Negociable',
city: 'Algiers',
phone: '71717171555',
email: 'test@test.com',
description: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
date: '28/11/2018',
userId: 5c25344c321f0d5a777ace00,
__v: 2 }

我确实阅读了有关populate的 Mongoose 文档,但我不知道如何填充userId以及如何填充comments和嵌套评论下的userId

最佳答案

假设 userId 是您的 Posts 架构中的一个字段,您可以这样做:

Posts.findOne({ id: 'your-post-id' })
.populate('userId')
.populate({ path: 'comments',
populate: { path: 'userId',
model:'User' }
})
.exec(callback);

您的架构应与此类似:

var postsSchema = new Schema({
comments: { type: [Schema.ObjectId], ref: 'Comment' },
userId: { type: Schema.ObjectId, ref: 'User' },
...
});
var commentsSchema = new Schema({
userId: { type: Schema.ObjectId, ref: 'User' },
...
});

关于javascript - Mongoose 复杂种群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53960601/

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