首页 > 解决方案 > Mongoose:使用填充数据构建查询

问题描述

我有一个包含组和用户的集合:

组架构:

const groupSchema = new mongoose.Schema({
    name: String,
    members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
});

用户架构:

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        min: 6,
        max: 255
    },
    email: {
        type: String,
        required: true,
        min: 5,
        max: 255
    },
    password: {
        type: String,
        require: true,
        min: 6,
        max: 1024,
    },
});

现在,我想构建一个查询来查找用户所属的所有组。我试图像这样构建它:

const userId = '...';
const groups = await Group.find({members: userId}).populate('members');

通过这个查询,我得到一个空数组,这不应该是结果。如何修复我的查询?

没有任何过滤器的查询结果如下所示:

[
    {
        "members": [
            {
                "_id": "6044c5d9b63a2a0ce0d0a32e",
                "name": "Test",
                "email": "test@test.com"
            }
        ],
        "_id": "6045e9837e66e80eca2a689c",
        "name": "Test",
        "__v": 0
    }
]

标签: javascriptnode.jsmongodbmongoose

解决方案


检查数据库中的数据后发现错误。问题是,members数组中的 id 存储为String. 将类型更改ObjectId为查询后工作正常。


推荐阅读