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

evi*_*iko 13 mongodb node.js

我想知道是否有办法插入新文件并一次性返回.

这就是我目前使用的:

db.collection('mycollection').insertOne(options, function (error, response) {
    ...
});
Run Code Online (Sandbox Code Playgroud)

Sha*_*Roy 43

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 
    }
});
Run Code Online (Sandbox Code Playgroud)

官方文件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

  • 有效!但是,当我执行`console.log(response)时,`ops`没有出现,这有点奇怪! (3认同)
  • 它与评估值时有关. (2认同)

ren*_*nan 11

对于那些使用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
      );
Run Code Online (Sandbox Code Playgroud)

请注意,_idintoInsert是新生成的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
      );
Run Code Online (Sandbox Code Playgroud)


Nav*_*r V 5

以下代码在MongoDB 版本 2.2.33 中对我有用。

db.collection("sample_collection").insertOne({
   field1: "abcde"
}, (err, result) => {
   if(err) console.log(err);
   else console.log(result.ops[0].field1)
}
Run Code Online (Sandbox Code Playgroud)