I have a collection that's called users. I have created another collection called roles. I am storing the role ids that belong to each user as an array of ObjectIds in their document:
{
"_id": {"$oid":"6137ad472e8f3841c2a2f485"},
"username":"atlante_avila",
"email":"atlanteavila@gmail.com",
"password":"$2a$08$1Nw42ciaahpt46FaV08ESukUa/uiDikQkxTs992E3P8h2ggHNb2AO",
"roles":[{"$oid":"6137ad032e8f3841c2a2f47d"}],
"__v":{"$numberInt":"1"}
}
I'd like to use something like db.collection("users").find()
and in that operation "populate" the roles field with the actual values from the roles collection. I can't really seem to find anything that shows you how to do that without using mongoose, I didn't start the project with mongoose so I don't really want to go through adding mongoose. Is there a way to do this without having to run a map and find every role that belongs to a particular user?
I have created this reusable findOne query:
dbManager.findOne = (collectionName, query, options) => {
options = options || {};
return new Promise((resolve, reject) => {
let collection = dbInstance.collection(collectionName);
__replaceId(query);
collection.findOne(query, options).then((doc) => {
return resolve(doc);
}).catch((err) => {
logger.error(err);
return reject(err);
});
});
}
which I'm using like this:
ObjectManager.findOne("users", {username: req.body.username}).then((user) => {
// do stuf with the user.
})
I'm wondering if there is something with the way I query or even the options that I pass in to "populate" the roles.