Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to get the values of an array of ObjectIds in using mongodb without mongoose

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!