Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading