简体   繁体   English

在 MongoDb ( Node.js ) 中返回插入的文档

[英]Return Inserted Document in MongoDb ( Node.js )

I need to insert one document to MongoDB and return the newly inserted document.我需要向 MongoDB 插入一个文档并返回新插入的文档。 I used db.collection('collection__name').insertOne('data to be inserted').then((res)=>{ res.send(res.ops[0]) })我使用了 db.collection('collection__name').insertOne('data to be insert').then((res)=>{ res.send(res.ops[0]) })

ERROR: ops is not defined.错误:未定义操作。

insertOne only returns the _id of the document inserted and not the whole document☹ but Earlier it used to return the whole document. insertOne 只返回插入的文档的_id,而不是整个文档☹,但之前它用于返回整个文档。 I used mongoclient and not mongoose and In mongoose it returns the whole doc but I don't like to work with mongoose.我使用 mongoclient 而不是 mongoose,在 mongoose 中它返回整个文档,但我不喜欢使用 mongoose。

They removed the ops field since mongo 4.0, you can find the schema here: https://mongodb.github.io/node-mongodb-native/4.0/interfaces/insertoneresult.html#insertedid他们从 mongo 4.0 开始删除了 ops 字段,你可以在这里找到架构: https : //mongodb.github.io/node-mongodb-native/4.0/interfaces/insertoneresult.html#insertedid

I just looked up the source code of mongoose and they are actually calling findOne based on the insertedId field:我刚刚查了 mongoose 的源代码,他们实际上是根据 insertId 字段调用 findOne :

    const promise = collection.insertOne({ foo: 'bar' }, {})
      .then(result =>
        collection.findOne({ _id: result.insertedId })
      ).then(doc => {
        assert.strictEqual(doc.foo, 'bar');
      });

( https://github.com/Automattic/mongoose/blob/80245edf5aeab304411681035f7f4153dbd2b692/test/collection.test.js#L50 ). https://github.com/Automattic/mongoose/blob/80245edf5aeab304411681035f7f4153dbd2b692/test/collection.test.js#L50 )。

It seems as the only solution is to either use an old library version (without typescript) or call findOne with the returned id field.似乎唯一的解决方案是使用旧的库版本(没有打字稿)或使用返回的 id 字段调用 findOne 。 I just had the same problem and added the additional findOne call, cause I didn't want to give up typescript.我只是遇到了同样的问题并添加了额外的 findOne 调用,因为我不想放弃打字稿。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM