I'm getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs and didn't find a proper way to do this. I was wondering what if it is at possible, and if so what is the proper way of doing such. Example: In the DB
{ user: "RMS", OS: "GNU/HURD", bearded: "yes", philosophy: { software: "FOSS", cryptology: "Necessary" }, email: { responds: "Yes", address: "[email protected]" }, facebook: {} } { user: "zuckerburg", os: "OSX", bearded: "no", philosophy: { software: "OSS", cryptology: "Optional" }, email: {}, facebook: { responds: "Sometimes", address: "https://www.facebook.com/zuck?fref=ts" } }
What would be the proper way of returning a field if it exists for a user, but if it doesn't return another field. For the example above I would want to return the [email][address]
field for RMS and the [facebook][address]
field for Zuckerburg. This is what I have tried to find if a field is null, but it doesn't appear to be working.
.populate('user' , `email.address`) .exec(function (err, subscription){ var key; var f; for(key in subscription){ if(subscription[key].facebook != null ){ console.log("user has fb"); } } }
If you only want a few specific fields to be returned for the populated documents, you can accomplish this by passing the field name syntax as the second argument to the populate method. Model . findOne({ _id: 'bogus' }) . populate('the_field_to_populate', 'name') // only return the Persons name ...
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have.
I'm not completely clear on what you mean by "returning a field", but you can use a lean()
query so that you can freely modify the output, then populate both fields and post-process the result to only keep the field you want:
.lean().populate('user', 'email.address facebook.address') .exec(function (err, subscription){ if (subscription.user.email.address) { delete subscription.user.facebook; } else { delete subscription.user.email; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With