简体   繁体   中英

Query nested property in Mongoose (without dot notation)

I am trying to query MongoDB using Mongoose to find documents based on the value of a nested property.

var Obj = new mongoose.Schema({
    mainProperty: {
      nestedProp1: String
      nestedProp2:String
    }
})

Due to the way the data is received, I need to perform the query without dot notation (as seen below).

Obj.find({'mainProperty.nestedProp': 'value'})

The code above will get me the correct results, but I need to pass in the query conditions in the format below.

Obj.find({ mainProperty: { nestedProp1: 'value' } })

I'm passing in the entire query object as an argument from on the client side, rather than developing the query on the server. By the time it hits the server, the code above appears as seen below.

Obj.find(queryCondition)
//queryCondition holds a value of { mainProperty: { nestedProp1: 'value' } }

Since there are two properties nested within mainProperty, it is not valid to perform the search above. It will search for documents that have mainProperty equal exactly to what is passed in following the colon (meaning documents that have a value equal to nestedProp1 and do not have a nestedProp2).

Is there another way to call this (without dot notation or editing the object itself) where it will query for the value of nestedProp1 rather than the value of mainProperty?

There is, you could do something like

const filter = {};

// check if you have specified nestedProp1
if ( req.body.nestedProp1 ) {
    filter['mainProperty.nestedProp1'] = req.body.nestedProp1;
}

if ( req.body.nestedProp2 ) {
    filter['mainProperty.nestedProp2'] = req.body.nestedProp2;
}

// and then
Obj.find( filter );

So if you have specified the filter, you will receive filtered records, otherwise the default records.

I haven't tested the code, so if this doesn't work you can try doing filter['mainProperty']['nestedProp1'] = req.body.nestedProp1;

You can use most Mongo DB syntax with Mongoose find() . Try this:

Obj.find({ mainProperty: { nestedProp1: { $in: ['value'] } } })

Mongo docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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