0

I have a mongoose query that will populate from other collection, then will match the populated's query, and then execute a callback function that will filter out null elements. The idea of the code is from https://stackoverflow.com/a/11418489/12773925. However, my return docs is not returning element to orders. Below is my code.

const orders = Order.find()
  .populate('buyer_id', null, { name: { $regex: localQuery } })
  .exec(function (err, docs) {
    docs = docs.filter(function (doc) {
      return doc.buyer_id != null;
    });

    return docs;
  });

When I do console.log(docs), it do have items in it.

The code used for console.log as belows:

const orders = Order.find()
  .populate('buyer_id', null, { name: { $regex: localQuery } })
  .exec(function (err, docs) {
    docs = docs.filter(function (doc) {
      return doc.buyer_id != null;
    });
    console.log(docs);
    return docs;
  });

The returned element as below:

[
  {
    status: 'Completed',
    orderdetails_id: [
      6017f4a79c62e77224b85644,
      6016d2edcc40583748e42908,
      601a4ea674e6ce505ccbd305
    ],
    _id: 6017587bbb33107e8c8f135a,
    buyer_id: {
      role: 'user',
      _id: 6013e314958b9a3570d04a04,
      name: 'Wan Amin',
      createdAt: 2021-01-29T10:27:32.123Z,
      updatedAt: 2021-02-09T07:29:18.396Z,
      __v: 78
    },
    address: [ [Object] ],
    total_price: 446,
    createdAt: 2021-02-01T01:25:15.999Z,
    updatedAt: 2021-02-19T15:44:55.605Z,
    __v: 9,
    driver_id: 60143a2e958b9a3570d04ae6
  }

However, when I check my orders, it is showing undefined.

1 Answer 1

1

you can use async/await

const orders = async ()=>{
  let docs = await Order.find().populate('buyer_id', null, { name: { $regex: localQuery } })
  docs = docs.filter(function (doc) { return doc.buyer_id != null; });
  return docs 
  }
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.