简体   繁体   English

如何编写一个mongoose查询来过滤子文档

[英]How to write a mongoose query to filter subdocuments

I have a Mongoose schema called "Users" which has a "Roles" subdocument as one of its variables like so: 我有一个名为“Users”的Mongoose模式,它有一个“Roles”子文档作为其变量之一,如下所示:

var UserSchema = new mongoose.Schema({
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    roles: [ { type: Number, ref: 'Role' } ]
});

var RoleSchema = new mongoose.Schema({
    _id: Number,
    name: { type: String, required: true, unique: true },
    description: { type: String, required: true }
});

I want to create a Mongoose query that will find all users with roles.names of "admin" or "owner". 我想创建一个Mongoose查询,该查询将查找role.names为“admin”或“owner”的所有用户。 I've tried using this query, which I thought would work, but I don't get any users when I use the where...in part. 我已经尝试过使用这个查询,我认为它可以工作,但是当我使用where...in部分时,我没有得到任何用户。

var roles = ["owner", "admin"];
User.find()
    .populate('roles')
    .where('roles.name').in(roles)
    .sort({'_id': 1})
    .exec(function (err, users) {
        res.send(users);
    });

Can someone tell me where my logic is wrong? 有人能告诉我我的逻辑错在哪里吗?

It's not possible to query more than one collection with a single query. 使用单个查询查询多个集合是不可能的。 If Role was an embedded subdocument in User then you could do a query on roles.name but presently that's not supported because it's a separate collection that is referenced in User . 如果RoleUser的嵌入式子文档,那么您可以对roles.name进行查询,但目前不支持,因为它是User引用的单独集合。

However, a workaround is to add another filter step after the query returns that manually filters out documents which don't have any roles that matched the populate criteria but first you need to use a match query in populate instead of where method: 但是,解决方法是在查询返回后添加另一个过滤器步骤,手动过滤掉没有任何与填充条件匹配的角色的文档,但首先需要在populate而不是where方法中使用匹配查询:

var roles = ["owner", "admin"];
User.find()
    .populate('roles', null, { name: { $in: roles } } )
    .sort({'_id': 1})
    .exec(function (err, users) {
        users = users.filter(function(user){
            return user.roles.length;
        });
        res.send(users);
    });

This is built into Mongoose populate() here . 这是内置到猫鼬populate() 这里 You can simply structure a query like this: 您可以简单地构建一个这样的查询:

 var roles = ["owner", "admin"];
 User.find()
    .populate({
        path: 'roles',
        match: { name: { $in: roles }},
        select: 'name'
    })
    .sort({'_id': 1})
    .exec(function (err, users) {

        res.send(users);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM