1

I need to get a bunch of records from a collection based on their Ids. This is my function:

const getClassesForIDs = (classIDArray) => {
   
    console.log('in model getClassesForIDs');
    
    return new Promise((resolve, reject) => {
        
        Class.aggregate([
            {
                $match: {_id:{$in:classIDArray.map(_post => {new mongoose.Types.ObjectId(_post)})}}
            },
        ]).exec(function (err, classData) {
            if (err) {
                reject(err);
            } else {
                resolve(classData);
            }
        })
    })
}
classIdArray = ["6091468e749cd2f796f01efd", "60923c997b4d3205009a981b"]

Even though there are records matching these Ids, this function returns an empty array. When I run it in MongoDB compass, it returns the correct record:

{
  "_id" : {$in: [ObjectId('6091468e749cd2f796f01efd'), ObjectId('60923c997b4d3205009a981b')]}
}

What am I missing?

1 Answer 1

3

The issues is in map function, correct this as below,

Remove bracket {} from map function or return the element through return keyword when you use {} bracket,

  • First syntax:
classIDArray.map(_post => new mongoose.Types.ObjectId(_post))
  • Second syntax:
classIDArray.map(_post => { return new mongoose.Types.ObjectId(_post) })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.