首页 > 解决方案 > MongoDB - 从另一个表中查找所有记录

问题描述

我有以下两个表:

注释 :

{
        "createdOn": "2020-03-08T04:19:20.276Z",
        "comment": "First comment in the app",
        "likesCount": 1,
        "_id": "5e6472c32fe18a59b1068f46",
        "userId": "5e60ec371dc3d30e61c6805b",
        "postId": "5e6356546d284c2cdfe1ad92",
        "__v": 0
    }

评论喜欢

{
        "createdOn": "2020-03-08T06:47:58.855Z",
        "_id": "5e64955abb6056610f802159",
        "userId": "5e60ec371dc3d30e61c6805b",
        "commentId": "5e6472c32fe18a59b1068f46",
        "__v": 0
    }

现在我正在尝试通过以下查询获得所有喜欢:-

Comments.aggregate([
    {$match: {postId : postId}},
    {$lookup:{
        from: 'commentLikes',
        localField: '_id',
        foreignField: 'commentId',
        as : 'likes'
    }}
    ])
.exec()

它不会返回任何类似的东西。我从这个查询中得到的响应是:-

{
        "_id": "5e6472c32fe18a59b1068f46",
        "createdOn": "2020-03-08T04:19:20.276Z",
        "comment": "First comment in the app",
        "likesCount": 1,
        "userId": "5e60ec371dc3d30e61c6805b",
        "postId": "5e6356546d284c2cdfe1ad92",
        "__v": 0,
        "likes": []
    }

不知道我在这里做错了什么。请帮忙。

标签: mongodbmongoosemongodb-queryaggregation-framework

解决方案


当大家都说查询没问题的时候,问题应该出在集合的名义上。然后我尝试使用以下代码获取我的收藏列表:-

mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
//trying to get collection names
mongoose.connection.db.listCollections().toArray(function (err, names) {
    console.log(names); // [{ name: 'dbname.myCollection' }]
    module.exports.Collection = names;
});})

我很惊讶猫鼬把所有系列的名字都改成了小写字母。集合名称commentLikes变成了 commentlikes。现在我的查询运行良好。


推荐阅读