What's the correct syntax for finding an element inside of an array with mongoose?

Advertisements

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 a file from the files array.

For all my other queries I’ve used something like this(non array):

const file = await Publication.find({files:req.body.fileId})

But it doesn’t seem to work since I’m not really accessing the files field.

Other queries I’ve tried have been: const file = await Publication.find({files._id:req.body.fileId})which gives syntax error.

And the last that I’ve tried being:const file = await Publication.find({files:[{_id:req.body.publicationId}]}) which returns null.

So my questions are:
Is there a way to do it similar to the way Im doing it? if so, what’s the syntax?
And in case I’m doing it completely wrong, what’s the intended way of doing it?

>Solution :

when querying a nested field, you should wrap it in quotes
like this:

const file = await Publication.findOne({ "files._id": req.body.fileId})

Leave a ReplyCancel reply