mongoose - 在 Model.create 中选择特定字段

ahm*_*ici 7 mongoose mongodb node.js

 const generatedEvent = await Event.create(req.body);
 res.send(generatedEvent);
Run Code Online (Sandbox Code Playgroud)

我从请求正文中获取一些数据,并且可以生成一个新事件。当事件生成时,我将其返回给客户端。但我不想返回带有事件的所有字段。我想进行过滤操作,就像我们如何使用这样的选择函数:Event.find().select({title:1,description:1}) How can i use this select func with Model.create?

eol*_*eol 3

如果您查看mongoose-source code,您可以看到它Model.create返回一个带有创建/插入文档的承诺。无法指定过滤选项仅返回特定字段。

当然,您可以在创建/插入新记录后.find()结合调用执行 a.select()操作,但这会导致每次插入都会产生一个额外的数据库查询,这没有多大意义。

您可以只从返回的文档中返回所需的属性,因为您知道当承诺解决时,已使用提供的数据成功插入了新文档。所以你可以简单地这样做:

res.send({title: generatedEvent.title, description: generatedEvent.description});
Run Code Online (Sandbox Code Playgroud)