Home > Net >  How to aggregate a newly created document in Mongoose?
How to aggregate a newly created document in Mongoose?

Time:11-22

I have a problem when using .create() to create new document, I need to $lookup aggregate 1 field in the document. The problem I am facing is .aggregate is not working on the returned document after created and I get an error if I try to do that: .aggregate is not a function. How can I do correctly aggregate a new created document ?

My code:

let newsDoc = await newsModel.create({...});
newsDoc = await newsDoc.aggregate([...]); // not working
res.status(200).send(newsDoc);

CodePudding user response:

.aggregate() method is a function inside the mongoose model instance, which is essentially a wrapper around the official MongoDB driver.

.create() returns the object that it has been created and not the model instance.

See this:

// Here newsDoc is the news document inserted and NOT the news Model 
let newsDoc = await newsModel.create({...});

// Hence this
// newsDoc = await newsDoc.aggregate([...]);
// Causes error

// For you to aggregate, use the model reference: 
// This would work
newsDoc = await newsModel.aggregate([...]); // not working

You can pass the _id that is returned from the create() method inside the aggregate() to filter out the object that is running currently in the context.

Hope it helps.

  • Related