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

202
Visualizações
Mongoose search by array entries ($in) behavior not aligned with MongoDB Atlas

I'm running a Node.js server, connecting to a MongoDB database with mongoose. Inside my controller, I have several methods that make operations to the database. One of them is this one:

async findMultiple(req, res) {
  const [baseSkillsArray] = Array(req.body);
  try {
    // if there is not baseSkillsArray, skip
    if (!baseSkillsArray) {
      return res.status(200).send([]);
    }
    // find all baseSkills using the ids in the baseSkillsArray
    const allBaseSkills = await BaseSkill.find({
      _id: { $in: [baseSkillsArray.baseSkillArray] } //
    });
    console.log('test ' + allBaseSkills);
    res.status(200).send(allBaseSkills);
  } catch (error) {
    console.error(error.message);
    res.status(500).send('Server error find BaseSkills');
  }
}

However, this returns me nothing. I did some debugging and I found the reason is the find id $in the array. So I tried hard coding a value, like '2', for instance.

// find all baseSkills using the ids in the baseSkillsArray
const allBaseSkills = await BaseSkill.find({ _id: { $in: ['2'] } });

No success. So I went to MongoDB Atlas, where my DB is stored. I tried filtering using the same line of code in my collections.

{ _id: { $in: ['2'] } }

Surprisingly, it returns my document as I wanted!

The issue is that I need to make it work with mongoose. Any ideas? Is this a known bug?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

There is nothing wrong with the query, nor a bug regarding $in.

In fact, what's wrong is the actual collection name. I manually created a collection in MongoDB Atlas, called "baseSkills". However, mongoose by default transforms your collection name into lowercase and adds an "s" if your collection's name is not in the plural.

So every time I started my server, I noticed that there was a new collection called "baseskills". I assumed it was a bug and deleted it. Only after making this post that I realized the collection was there again.

So I exported the documents to this collection and my query was working fine.

FYI, there is a way to enforce the collection's name in mongoose. When you declare you model, add a second parameter to the Schema function called "collection". Here is an example:

const BaseSkillSchema = new mongoose.Schema({
  _id: {
    type: String,
    required: true
  }, ...
}, { collection: 'baseSkills' })

That's it! Sorry for the mess and thank you for your help!

about 4 years ago · Santiago Trujillo Relatório

0

you want to query over mongo db object ids. So you should create a new ObjectId to do that.

import {Types} from 'mongoose';

{ _id: { $in: [new Types.Object("2")] } }

Or if you have 2 ids one generated and one custom created as id then you can query without creating a new object.

{ id: { $in: ['2'] } }

about 4 years ago · Santiago Trujillo Relatório
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