我有两个收藏品
1)用户 - >有了字段,
name as String
emailId as String
2)
评级 - >有了字段,
`userId as String.` (This will be the ID of the user and Foreign Key as per SQL)
comment as String`
我为用户创建了一个类似
的记录{
"_id": {
"$oid": "565fe1294a27a93449751a9a"
},
"name": "Some name",
"email": "somemail@gmail.com",
"createdAt": {
"$date": "2015-12-03T06:28:57.904Z"
},
"updatedAt": {
"$date": "2015-12-03T06:28:57.904Z"
}
}
我为评级创建了一个类似
的记录{
"_id": {
"$oid": "565fefa30878764428d96be1"
},
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment",
"createdAt": {
"$date": "2015-12-03T07:30:43.409Z"
},
"updatedAt": {
"$date": "2015-12-03T07:30:43.409Z"
}
}
现在我想进行查询,其中返回用户完成的所有评级以及用户文档。
如果我查询
db.user.find({
"userId" :"565fe1294a27a93449751a9a"
})
我得到的结果如
{
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
}
但我想要的用户对象就像。
{
"id": "565fefa30878764428d96be1",
"user": { "name": "Some name",
"email": "somemail@gmail.com",
"id": "565fe1294a27a93449751a9a"
},
"comment": "just a test comment"
}
或者甚至这样的东西也会起作用
"rating": {
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
},
"user": {
"id": "565fefa30878764428d96be1",
"userId": "565fe1294a27a93449751a9a",
"comment": "just a test comment"
}
答案 0 :(得分:0)
您需要更改架构。您需要将用户类型从字符串更改为引用。如果您在评级中添加User的引用,那么这将很容易。如果添加用户架构的引用,则可以在评级上填充用户。然后将获得评级的用户信息。
参考示例:
User: {type: mongoose.Schema.ObjectId, ref: 'User'}
答案 1 :(得分:0)
在这里找到我的确切解决方案。 http://sailsjs.org/documentation/concepts/models-and-orm/associations/one-to-many
从技术上讲,它会在后端创建两个查询。通过响应时间找到了这个。
但无论如何它解决了我的问题。