簡體   English   中英

Node.js + MongoDB:插入一個並返回新插入的文檔

[英]Node.js + MongoDB: insert one and return the newly inserted document

我想知道是否有辦法插入新文檔並將其返回到一個 go 中。

這是我目前正在使用的:

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

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

以下代碼對我有用,在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)
}

你可以使用貓鼬來做到這一點。 使用save方法,您可以插入文檔並在成功時返回它。 這是貓鼬文檔中的一個示例:

product.save(function (err, product, numAffected) {
  if (err) {
    // Handle error...
  } else {
    // Do something with the returned document...
  }
})

發布此信息,因為這可能對某人有所幫助。 您可以像這樣找到更新的對象:

await req.db
    .collection('users')
    .insertOne({ email, password: hashedPassword, name  })
    .then(({ ops }) => ops[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
      );

注意toInsert中的_id是一個新生成的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
      );

你可以使用mongojs來做到這一點。

db.collection('mycollection').save(doc, function(error, response){
  // response has _id
})

試試這個

try {
    let collection = db.collection('collection_name'); let { ops: inserted } = 
    await collection.insertOne({ data: object });
    // can access array of inserted record like :
    console.log(inserted)
 } catch (error) {
    // log errors
 }

我想仍然使用 .then() 通過插入來解決,所以我最終將所有內容都包裝在它自己的承諾中。

 return new Promise((resolve, reject) => {
     db.collection('entries').insertOne({ entry }, (err, res) => {
     if (err) {
       console.log('error', err);
       reject(null);
     } else {
       resolve(res.ops[0]);
     }
   });
 });

那我就可以做

 insertEntry({}).then(entry=>{})

最新的 v4 行為

正如勞倫在官方 mongodb 論壇中所說,這是預期的行為。 我在這里復制她的回復:

我們的驅動程序符合 MongoDB CRUD 規范,這是驅動程序 v4 中的新功能

當你insertOne你現在得到insertedId ,所以它應該提供由數據庫處理的文檔的唯一“新”部分。

    const myDoc = { a: 1 }
    myDoc._id = (await c.insertOne(myDoc)).insertedId
    // myDoc is now the same as the doc inserted into mongodb 

您可以返回使用 id 插入的文檔

async insertProduct(product) {
  const record = await db.collection("products").insertOne(product);
  return {id: record.insertedId, ...product }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM