简体   繁体   中英

Dot notation on nested objects not in Mongoose schema

I have a mongoose schema with a providerData object:

... , providerData: {}, ...

and I would like to query for documents based on the IDs of objects in the providerData object.

So I assumed I would have to use dot notation like so:

    User.findOne({ providerIDString: providerID }, function(err, user) {...});

where

    providerIDString is a string like 'providerData.facebook.id'
    providerID is the providerData.facebook id

However the query keeps returning no results even though

db.users.find({"providerData.facebook.id":"THEFACEBOOKID"})

in the mongodb shell returns the correct document

Am I correct to assume this is happening because providerData.facebook and providerData.facebook.id are not defined in the User schema?

Does this mean I have to add them to the schema or is there a way to use dot notation on nested objects not in the mongoose schema?

I'm guessing that you have input like:

var providerIdString = 'providerData.facebook.id',
    facebookId = "THEFACEBOOKID";

In which case you use:

var query = {};
query[provoderIdString] = facebookId;

Then:

db.users.find(query);

And behold! It works.

That is how you construct objects from variable names in JavaScript.

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