So I'm trying to fetch a set of company member documents that correspond to a specific user, and populate the company field of each document in the process. The aim here is to get the _id and the name fields of each company document that corresponds to a company member. I've been successful in fetching the company member documents, however, the _id field of each populated company is returned together with the "new ObjectId()" constructor as shown below:
The company members: [
{
company: { _id: new ObjectId("6296180fj2a538be87f058f"), name: 'aaa' }
}
]
Of course, the desired outcome is to get only the _id content without the ObjectId() constructor. I've tried using the method suggested in the accepted answer of this StackOverflow post, however, I got the same results (meaning the ObjectId() constructor didn't go away):
// Fetch up to 10 company members and populate their companies.
let companyMembers = await CompanyMember.find({user: user_id}, {_id: 0, company: 1}).populate({
path: 'company',
match: { name: { $regex : new RegExp(company_name, "i") } },
select: { _id: {"$toString": "$_id"}, name: 1 }
}).limit(10).exec();
CodePudding user response:
Have you tried lean()
funtion ?