我有一个端点,它给了我所有可用配置文件的列表,现在我有一个帖子架构和配置文件架构,我想添加一个特定用户对我的结果发布的帖子列表
终结点中存在的代码
const profiles = await Profile.find()
.populate('user', [
'name',
'avatar'
])
配置文件架构
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
post: [],
........
发布架构
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
text: {
type: String,
required: true
},
........
响应
[
{
"social": {
"youtube": "https://youtube.com/.",
"twitter": "https://twitter.com/.",
"facebook": "https://fb.com/."
},
"post": [], //This should populate
"skills": [
"HTML",
"CSS",
"PHP",
"Ruby"
],
"_id": "5ced6cb9e3f7485ee2cb0445",
"user": {
"_id": "5ced02551b60fe20afc72a32",
"name": "John abc",
"avatar": "//www.gravatar.com/avatar/1f9d9a9efc2f523b2f09629444632b5c?s=200&r=pg&d=mm"
},
"status": "Developer",
"experience": [
{
"current": true,
"_id": "5ceebb30bb0c667b85a94f97",
"from": "2010-08-09T18:30:00.000Z",
"description": "lorem ipasum"
}
],
"date": "2019-05-28T17:15:37.755Z",
"__v": 30,
"bio": "I am dev",
"education": [
{
"current": false,
"_id": "5cf0c1dc6b8dc33cd68be560",
"degree": "BE",
"from": "2005-07-09T18:30:00.000Z",
"to": "2010-03-03T18:30:00.000Z",
"description": "Got BE"
}
]
}
]
预期产出
[
{
"social": {
"youtube": "https://youtube.com/.",
"twitter": "https://twitter.com/.",
"facebook": "https://fb.com/."
},
"post": [
{_id:98as98djakjbkasd,
text:"This is post by xyz user"
},
{_id:234oijaoijd,
text:"This is another post by xyz user"
}
]
"skills": [
"HTML",
"CSS",
"PHP",
"Ruby"
],
"_id": "5ced6cb9e3f7485ee2cb0445",
"user": {
"_id": "5ced02551b60fe20afc72a32",
"name": "John abc",
"avatar": "//www.gravatar.com/avatar/1f9d9a9efc2f523b2f09629444632b5c?s=200&r=pg&d=mm"
},
.....
我想填充同一用户完成的帖子,需要在端点代码中进行哪些更改。
我是猫鼬的新手,在寻找解决方案时aggregate
我发现这些解决方案可能有用,但不能像.find().aggregate([...])
一样使用
尝试加入MongoDB会破坏使用MongoDB的目的。当我们首先考虑我们的用例,然后决定数据库和模式时。但是,您可以使用 DBref 并编写自己的应用程序代码。
另一件事,您可以将架构更改为单个集合并使用嵌入文档
MongoDB总是建议避免加入我们的查询!