【发布时间】:2020-03-14 14:47:59
【问题描述】:
对于 Mongoose 的帮助,我将不胜感激。我有 3 个表:(用户)用户表,(动物)动物表和表 AnimalComments。所以(AnimalComments)表参考用户和动物。
const schemaComment = new mongoose.Schema({
userRef: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
animalRef: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Animal'
},
content: {
type: String
}
});
const schemaAnimal = new mongoose.Schema({
name: {
type: String
},
isCommentedByMe: {
type : Boolean,
default: false
},
commentCount: {
type : Number,
default: 0
}
});
我想要什么:我有动物。用户可以为动物添加评论。当用户评论动物时,他的评论被添加到表 AnimalComments 中,其中存储了 userRef (userId)、animalRef (animalId) 和用户评论文本。然后在请求响应中,我想返回表 Animals 中的所有动物,但我需要根据表 AnimalComments 中的值更新属性 commentCount 和 isCommentedByMe。
Table Animals 的回应:
{
"animals": [
{
"isCommentedByMe": false,
"commentCount": 0,
"name": "Jessica",
"userRef": {
"id": "5dc9bdf3dd5cae00177e184d"
},
"id": "5dcedd48368e9800176f2ef3"
}
]
}
来自表用户的回应:
{
"users": [
{
"name": "Jony Cash",
"id": "5dc9bdf3dd5cae00177e184d"
}
]
}
AnimalComments 表的回复:
{
"comments": [
{
"userRef": "5dc9bdf3dd5cae00177e184d",
"animalRef": "5dcedd48368e9800176f2ef3",
"content": "Sample text"
}
]
}
我想要例如结果:
{
"animals": [
{
"isCommentedByMe": true,
"commentCount": 4,
"name": "Jessica",
"userRef": {
"id": "5dc9bdf3dd5cae00177e184d"
},
"id": "5dcedd48368e9800176f2ef3"
}
]
}
【问题讨论】:
-
如果你能给出预期的结果,就很容易理解你想要什么。
-
我认为您的数据模型有点错误。根据已经存储的内容设置一个属性并不是一个好主意。无需将
allLikeCount设置为所有评论喜欢的计数,只需在每次需要时汇总评论喜欢。这将确保数据永远不会不同步,并始终提供最准确和最新的结果。 -
@SuleymanSah 我更新了我的问题应该更清楚
-
@chrispytoes 我更新了我的问题应该更清楚
-
请提供一些示例输入文件,以及预期的输出文件
标签: node.js database mongodb mongoose populate