1

This is my ObjectIds array -

obj_ids = [
    "5ee71cc94be8d0180c1b63db",
    "5ee71c884be8d0180c1b63d9",
    "5ee71c494be8d0180c1b63d6",
    "5ee71bfd4be8d0180c1b63d4"
]

I am using these objectids to serach whether they exist in the db or not and based on that I want to send the response to server. This is the code I am trying but I dont know how to populate the array and send it to the server.

var msg = [];
obj_ids.map((ele) => {
    Lead.find({ _id: ele._id }, async function (error, docs) {
        if (docs.length) {
            msg.push(
                `Lead already exist for Lead id - ${ele._id} assgined to ${docs[0].salesPerson}`
            );
        } else {
            msg.push(`Lead doesn't exist for Lead id: ${ele._id}`);
            const newDuty = new AssignedDuty({
                duty: ele._id,
                salesPerson: req.body.salesPerson,
            });

            await newDuty.save();
        }
    });
});
res.json(msg);

By doing this approach I am getting an empty array. I cannot put res.json(msg) inside the loop. If it is possible by using async-await, please guide me through.

Charlie
  • 22,886
  • 11
  • 59
  • 90

1 Answers1

1

You don't need to make multiple queries to find whether given object ids exist in the database.

Using $in operator, you can make one query that will return all the documents where the _id is equal to one of the object id in the list.

const docs = await Lead.find({
    _id: {
        $in: [
          "5ee71cc94be8d0180c1b63db",
          "5ee71c884be8d0180c1b63d9",
          "5ee71c494be8d0180c1b63d6",
          "5ee71bfd4be8d0180c1b63d4"
       ]
    }
});

After this query, you can check which object id is present in the docs array and which is absent.

For details on $in operator, see $in comparison operator

Your code can be simplified as shown below:

const obj_ids = [
    "5ee71cc94be8d0180c1b63db",
    "5ee71c884be8d0180c1b63d9",
    "5ee71c494be8d0180c1b63d6",
    "5ee71bfd4be8d0180c1b63d4"
];

const docs = await Lead.find({
    _id: { $in: obj_ids }
});

const msg = [];

obj_ids.forEach(async (id) => {
    const doc = docs.find(d => d._id == id);

    if (doc) {
        msg.push(
            `Lead already exist for Lead id - ${doc._id} assgined to ${doc.salesPerson}`
        );
    }
    else {
        msg.push(`Lead doesn't exist for Lead id: ${id}`);
        const newDuty = new AssignedDuty({
            duty: id,
            salesPerson: req.body.salesPerson
        });

        await newDuty.save();
    }
});

res.json(msg);
Yousaf
  • 27,861
  • 6
  • 44
  • 69