Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose - select specific fields in Model.create

 const generatedEvent = await Event.create(req.body);
 res.send(generatedEvent);

I am getting some data from the request body and I can generate a new Event. And I'm returning the event to client when it has generated. But I don't want to return all fields with event. I want to make filter operation like how we are using select function like this: Event.find().select({title:1,description:1}) How can i use this select func with Model.create?

like image 871
ahmetbcakici Avatar asked Aug 10 '26 16:08

ahmetbcakici


1 Answers

If you take a look at the mongoose-source code, you can see that Model.create returns a promise with the created/inserted documents. There's no way to specify a filtering-options to return only specific fields.

Of course you could do a .find() in combination with a .select() call after creating/inserting a new record but that would result in one extra DB-query for each insert which does not make a lot of sense.

You could instead just return the desired properties from the returned document, since you know that a new document was inserted successfully with the provided data, when the promise resolved. So you could simply do:

res.send({title: generatedEvent.title, description: generatedEvent.description});
like image 92
eol Avatar answered Aug 12 '26 10:08

eol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!