Node.js MongoDB:插入一个并返回新插入的文档

新手上路,请多包涵

我想知道是否有一种方法可以插入新文档并一次性返回。

这是我目前正在使用的:

 db.collection('mycollection').insertOne(options, function (error, response) {
    ...
});

原文由 evilReiko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 651
2 个回答

2021 年更新: 此方法 不再适用 于 MongoDB 驱动程序 4.x。 insertOne的返回结果只包含一个ID和确认标志: https ://mongodb.github.io/node-mongodb-native/4.1/interfaces/InsertOneResult.html

通过此更改,无法完成所需的行为。应该执行另一个 DB 请求或将返回的 insertId 和原始对象数据结合起来。


response 结果包含有关命令是否成功以及插入的记录数的信息。

如果要返回插入的数据,可以尝试 response.ops ,例如:

 db.collection('mycollection').insertOne(doc, function (error, response) {
    if(error) {
        console.log('Error occurred while inserting');
       // return
    } else {
       console.log('inserted record', response.ops[0]);
      // return
    }
});

insertOne 的官方文档:

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne

callback 类型:

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpCallback

result 类型:

http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult

原文由 Shaishab Roy 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些使用 MongoDB 驱动程序 4.x 的人,我找到了 findOneAndUpdate 的解决方法:

       const toInsert = {
        _id: mongo.ObjectId(),
        someField: 'hello',
        someOtherField: 'world'
      };
      const options = { upsert: true, returnDocument: 'after' };
      const { value: document } = await db.collection.findOneAndUpdate(
        toInsert,
        { $set: {} },
        options
      );

注意 _id 中的 toInsert 是新生成的 ObjectId

更新是空的( { $set: {} } )并且什么都不做,因为我们不需要更新,我们只想更新我们的文档。仍然需要它,因为更新不能是 null 或空对象。

由于 returnDocument 选项,新创建的文档将作为结果中的值返回。


为了避免空更新,另一种解决方案是使用 $setOnInsert

       const toInsert = { someField: 'hello', someOtherField: 'world' };
      const options = { upsert: true, returnDocument: 'after' };
      const { value: document } = await db.collection.findOneAndUpdate(
        { _id: mongo.ObjectId() },
        { $setOnInsert: toInsert },
        options
      );

原文由 renan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题