Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda