node.jsmongodbmongoose

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?


Solution

  • 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});