在MongoDB中查询内部ID

在MongoDB中查询内部ID,mongodb,mongodb-query,Mongodb,Mongodb Query,我有两套 1) 用户->带字段 name as String emailId as String `userId as String.` (This will be the ID of the user and Foreign Key as per SQL) comment as String` (二) 评级->带字段 name as String emailId as String `userId as String.` (This will be the ID of the us

我有两套

1) 用户->带字段

name as String
emailId as String
 `userId as String.` (This will be the ID of the user and Foreign Key as per SQL)
 comment as String`
(二)

评级->带字段

name as String
emailId as String
 `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"
    }
}
我已经创建了一个评级记录,看起来像

{
    "_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"
}

在这里,您需要更改模式。您需要将用户类型从字符串更改为引用。如果您在评级中添加用户参考,那么这将很容易。若您添加了对用户模式的引用,那个么您可以在评级时填充用户。然后将获得带有评级的用户信息

参考示例:

User: {type: mongoose.Schema.ObjectId, ref: 'User'}

找到了我的精确解

从技术上讲,它在后端创建两个查询。通过响应时间发现了这一点


但无论如何,它解决了我的问题。

我使用了帆船和吃水线,根据本文档,我没有看到参考类型。你需要和mongodb合作。检查此链接:谢谢,但我在这里得到了确切的解决方案。