Search code examples
javascriptnode.jsdatabasemongodbmongoose

Using map() function of javascript inside the find() method of mongoose


Earlier I was using this piece of code for db call fetch data.

const projectOffering = await ProjectOfferingsBudgets.find({ objectiveId: tracker.objectives.map((id)=>id)  }).lean().exec();

The "objectiveId" is a ObjectId type and my tracker. objectives contain an array of id(ObjectId), so I want to retrieve data from the database where this array of id matches to objectiveId in "ProjectOfferingsBudgets" collection.

But one of my colleagues told me this won't work instead try this code.

const projectOffering = await ProjectOfferingsBudgets.find({ objectiveId: { $in: tracker.objectives }  }).lean().exec();

I have tried to console the result of the 2 different codes but I am receiving the same results.
In the database, it matches 2 documents and I am getting those 2 documents in return for my code as well as my colleague's code.
So what I am asking is can we use map() inside find() method if not then why I am getting the accepted result?


Solution

  • The mongoose find() is very forgiving. While it seems counter-intuitive the find() method will work perfectly fine being passed an array in this case as you have found out. It is more semantic using the $in operator but these examples below return identical results. Given an array of ObjectIds:

    const arr = [
       new ObjectId("650ecb0f507561a33ce927aa"), 
       new ObjectId("65128fb671522f4d58dabd55")
    ];
    

    Both these queries return the same results:

    const users1 = await Model.find({_id: arr}); //< Pass just the array
    
    const users2 = await Model.find({_id: {$in: arr}}); //< Pass array using $in
    

    To answer your last question "So what I am asking is can we use map() inside find() method". Then yes, you can run a function as long as it's return value is something the enclosing function expects as a parameter then you can of course call it.