Home > Software design >  How to get an array element in the same index as the query in mongoose
How to get an array element in the same index as the query in mongoose

Time:11-28

I have the following Schema:

const PublicationSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    files:[{ 
        contentType: String, 
        data: Buffer,
        name: String
    }]

})

What I'm trying to do is to get the file with the same index as the query.For example I have this object:

  _id: new ObjectId("637f20ce6ce5c48d9788a1ff"),
  title: 'TEST',
  files: [
    {
      contentType: 'application/pdf',
      name: 'imId1',
      _id: new ObjectId("id1")
    },
    {
      contentType: 'application/pdf',
      name: 'imId2',
      _id: new ObjectId("id2")
    }
  ]

where if I query id2 it only retrieves:

    {
      contentType: 'application/pdf',
      name: 'imId2',
      _id: new ObjectId("id2")
    }

What I was trying to use was const onePublication = await Publication.findOne({ "files._id": req.body.fileId},{}) but this retrieves every field.

I was going to just tell it to not retrieve the other field using field:0 but I realized that this will still retrieve the files in other indexes of the field.

Is there a way to tell it to only retrieve the one with the same index or should I be using another query entirely?

CodePudding user response:

One of the options is to $unwind the array first. $match by your criteria. Then, $replaceRoot to get your array entry.

db.collection.aggregate([
  {
    "$unwind": "$files"
  },
  {
    $match: {
      "files._id": "id2"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$files"
    }
  }
])

Mongo Playground

Consider changing your schema to store files as an individual collection, if most of the time you are going to access the array objects only.

  • Related