Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda