Home > front end >  Mongoose search by array entries ($in) behavior not aligned with MongoDB Atlas
Mongoose search by array entries ($in) behavior not aligned with MongoDB Atlas

Time:08-15

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?

CodePudding user response:

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'] } }

CodePudding user response:

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!

  • Related