简体   繁体   English

MongoDb查询嵌套对象的数组字段

[英]MongoDb Query on array field of a nested object

I'm trying to query all users that favorited an event. 我正在尝试查询喜欢该事件的所有用户。 The event Id is stored in the users document in a nested object. 事件ID存储在用户文档的嵌套对象中。

My schema looks like this 我的架构看起来像这样

{
    email: {
      type: String,
      unique: true,
      required: [true, 'Email is required!'],
      trim: true,
      validate: {
        validator(email) {
          const emailRegex = /^[-a-z0-9%S_+]+(\.[-a-z0-9%S_+]+)*@(?:[a-z0-9-]{1,63}\.){1,125}[a-z]{2,63}$/i;
          return emailRegex.test(email);
        },
        message: '{VALUE} is not a valid email!',
      },
    },
    role: {
      type: String,
      enum: ['admin', 'user', 'planner'],
      default: 'user',
    },
    name: {
      type: String,
      trim: true,
    },
    username: {
      type: String,
      trim: true,
      unique: true,
    },
    password: {
      type: String,
      required: [true, 'Password is required!'],
      trim: true,
      minlength: [6, 'Password needs to be longer!'],
      validate: {
        validator(password) {
          return password.length >= 6 && password.match(/\d+/g);
        },
      },
    },
    picture: {type: String},
    favorites: {
      events: [
        {
          type: Schema.Types.ObjectId,
          ref: 'Event',
        },
      ],
    },
  }

How would I write this query? 我将如何编写此查询?

I've tried all kinds of combinations with $elemMatch and normal queries aswell 我已经尝试过$elemMatch和普通查询的各种组合

$elemMatch should be used as an object, but in array favorites.events each element is String (ObjectID), so you should use $eq to match each element with String which is ID of event you want. $elemMatch应该用作对象,但在数组favorites.events每个元素都是String(ObjectID),因此,应使用$eq将每个元素与String匹配,String是所需事件的ID。

The solution is: 解决方案是:

User.find({
    'favorites.events': {
        '$elemMatch': {
            '$eq': id
        }
    }
})

Document for $elemMatch here https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#element-match $elemMatch文档在这里https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#element-match

And document for $eq here https://docs.mongodb.com/manual/reference/operator/query/eq/ $eq文档在这里https://docs.mongodb.com/manual/reference/operator/query/eq/

You should question with simple structure of Mongo. 您应该对Mongo的简单结构提出疑问。 Example, this is my test for you problem 例如,这是我为您测试的问题

const Schema = mongoose.Schema;

const EventSchema = new Schema({
    title: String
})

const UserSchema = new Schema({
    username: String,
    favorites: {
        events: [{
            type: Schema.Types.ObjectId,
            ref: 'Event',
        }]
    }
});

const User = mongoose.model('User', UserSchema);
const Event = mongoose.model('Event', EventSchema)

app.get('/users/event/:id', (req, res) => {
    const {id} = req.params;
    console.log(id);
    User.find({
        'favorites.events': {
            '$elemMatch': {
                '$eq': id
            }
        }
    }).then(u => res.send(u)) })

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

相关问题 MongoDB查询以查找字段中嵌套数组或对象的元素值类型 - Mongodb query to find element value type of nested array or object in a field MongoDb查询以在嵌套数组中查找特定对象 - MongoDb query to find specific object in nested array Mongodb:查询嵌套在数组中的json对象 - Mongodb: Query a json-object nested in an array MongoDB 查询特定 object 的嵌套数组 - MongoDB query for nested array of specific object 将嵌套的 object 字段合并为 MongoDB 聚合中的单个嵌套数组字段 - Merging nested object fields into a single nested array field in MongoDB Aggregation Mongodb:如何转换 object 嵌套数组中的字段 - Mongodb : How to convert a field inside a nested array of object 在 mongoDb 中,如何重命名嵌套的字段,如 object-> object -> array -> object -> field? - In mongoDb, how can I rename a field nested like object-> object -> array -> object -> field? MongoDB 通过 ID 查询和更新嵌套数组中的单个 object? - MongoDB query and update single object inside nested array by ID? 查询数组对象中的自动生成Shortid字段是不是在mongodb上工作? - Query for a auto generate Shortid field in an object of array is not working on mongodb? MongoDB查询IN对象数组 - MongoDB query IN array of object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM