mongoose - select specific fields in Model.create

Viewed 2218
 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?

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

Model.create() internally doesn't fetch the document from the database, rather it actually returns the result whether it's inserted successfully or not. If successful, mongoose will return the original mongoose document that mongoose created before sending to the database.

So you could just select the fields by yourself. Using es2015 Object destructuring assignment and Object shorthand property names would help writing more concise code.

const { title, description } = await Event.create(req.body); // Object destructuring
res.send({ title, description }); // Object shorthand property names
Related