NodeJSのMongoデータベースに挿入されたドキュメントの_idを取得する


100

NodeJSを使用して、MongoDBにドキュメントを挿入します。使用してcollection.insert、私はこのコードのようにデータベースに文書を挿入することができます。

// ...
collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId; // = ???
});
// ...

_id挿入されたオブジェクトの取得方法を教えてください。

_id最新のオブジェクトを挿入せずにを取得する方法はあります_idか?

多くの人が同時にデータベースにアクセスすると仮定すると、最新のIDが挿入されたオブジェクトのIDであるかどうか確信が持てません。

回答:


88

コールバックには2番目のパラメーターがあり、collection.insert挿入された1つまたは複数のドキュメントを返します。これには_idが必要です。

試してください:

collection.insert(objectToInsert, function(err,docsInserted){
    console.log(docsInserted);
});

そして、コンソールをチェックして、私の意味を確認してください。


4
コールバックは実際に挿入されたドキュメントの配列を返します。したがって、1つのドキュメントを挿入した場合は、以下のように挿入したレコードにアクセスできます。collection.insert({name: "David"、title: "About MongoDB"}、function(err、records){console.log( "Record added as" + records [0] ._ id);}); 参照:mongodb.github.io/node-mongodb-native/markdown-docs/insert.html
Rohit Singh Sengar 14年

2
コールバックAPIが変更されました:mongodb.github.io/node-mongodb-native/2.0/api/...
tenbits

リンクが役に立たない場所につながる
davidhadas

これが一般的なものか流星でのみ機能するかはわかりませんが、collection.insert(object)を呼び出すと、挿入されたオブジェクトのIDがすぐに返されます。
vantesllar 2016年

4
docsInsertedは_idを返しません。返されます{"ok":1、 "n":1、 "opTime":{"ts": "6361004504208375809"、 "t":5}、 "electionId": "7fffffff0000000000000005"}
user1709076

90

のコールバックに2番目のパラメーターを使用するよりも短い方法は、をcollection.insert使用objectToInsert._idして_id(コールバック関数の内部で、操作が成功したと仮定した場合)です。

NodeJSのMongoドライバーは_idフィールドを元のオブジェクト参照に追加するため、元のオブジェクトを使用して挿入されたIDを簡単に取得できます。

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

4
非常に洞察力のあるありがとうございます。コールバックパラメータが変更されたため、他の場所でこの情報を見つけることができませんでした。
Brad Hein

@BradHeinどういたしまして!おそらくMongoDBドライバーがオブジェクト参照を変更するため、ここでも変更されます。:)
IonicăBizău

あなたのコードは間違っています、あなたは言うvar objectId = objectToInsert._id; var objectId = objectInserted._id;と言うつもりでした。
Andy Lorenz

3
@AndyLorenzとは何objectInsertedですか?この答えの要点が正確に欠けていると思います。Mongoドライバーは、_idフィールドを元のオブジェクトに追加します。objectToInsertどこでも使えるように回答を編集しました。物事がより明確になることを願っています。:)
IonicăBizău

1
注:insert()は非推奨です。insertOne()代わりに使用してください
evilReiko 2016年

16

ktretyakが言ったように、挿入されたドキュメントのIDを取得する最良の方法は、結果オブジェクトでInsertedIdプロパティを使用することです。私の場合、result._idが機能しなかったため、以下を使用する必要がありました。

db.collection("collection-name")
  .insertOne(document)
  .then(result => {
    console.log(result.insertedId);
  })
  .catch(err => {
    // handle error
  });

コールバックを使用する場合も同様です。


13

実際には、挿入用のコールバック関数の2番目のパラメーターに対してconsole.log()を実行しました。挿入されたオブジェクト自体とは別に、実際には多くの情報が返されます。したがって、以下のコードは、IDにアクセスする方法を説明しています。

collection.insert(objToInsert, function (err, result){
    if(err)console.log(err);
    else {
        console.log(result["ops"][0]["_id"]);
        // The above statement will output the id of the 
        // inserted object
       }
});

これはを出力しObjectID {_bsontype: "ObjectID", id: Buffer(12)}ます。データベースにある実際のIDを取得するためにそれをどのように使用できますか?...別のコメントで答えを見つけました:使用result.insertedId.toString()
Fadwa

7

Mongoは完全なドキュメントをコールバックオブジェクトとして送信するため、そこからのみ取得できます。

例えば

collection.save(function(err,room){
  var newRoomId = room._id;
  });

4

これで、insertOneメソッドとpromiseの結果を使用できます。insertedId


コード例を提供できますか?この結果オブジェクトはどこから来たのですか?
JSideris 2016

@JSideris、仕様メソッドinsertOne()わかるように、このメソッドは3つのパラメーターを受け入れます(doc, options, callback)。3番目のパラメーター-2つのパラメーターを 受け取るコールバック(error, result)。そしてresult-これはあなたが探しているものです。
ktretyak 2016

2

@ JSideris、insertedIdを取得するためのサンプルコード。

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });

2

「_id」を使用する場合は、簡単に使用してください

result.insertedId.toString() 

// toStringは16進数から変換されます


それが私が探していたものです。ありがとうございました。
Fadwa

他の回答には言及していないので、いや、バージョン変更があったに違いないresult.insertedIdですObjectID型オブジェクト。.toString()このオブジェクトを実際のUUIDに変換します。
ディランピアス

0

非同期関数を使用して、データオブジェクトを操作せずに_idフィールドを自動的に取得できます。

async function save() {
  const data = {
    name: "John"
  }

  await db.collection('users', data )

  return data
}

データを返します:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}

0

非同期関数でそれを行う別の方法:

const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()

// Create.R.U.D
router.post('/new-order', async function (req, res, next) {

    // security check
    if (Object.keys(req.body).length === 0) {
        res.status(404).send({
            msg: "Error",
            code: 404
        });
        return;
    }

    try {

        // operations
        let orderNumber = await db.collection('orders').countDocuments()
        let number = orderNumber + 1
        let order = {
            number: number,
            customer: req.body.customer,
            products: req.body.products,
            totalProducts: req.body.totalProducts,
            totalCost: req.body.totalCost,
            type: req.body.type,
            time: req.body.time,
            date: req.body.date,
            timeStamp: Date.now(),

        }

        if (req.body.direction) {
            order.direction = req.body.direction
        }

        if (req.body.specialRequests) {
            order.specialRequests = req.body.specialRequests
        }

        // Here newOrder will store some informations in result of this process.
        // You can find the inserted id and some informations there too.
        
        let newOrder = await db.collection('orders').insertOne({...order})

        if (newOrder) {

            // MARK: Server response
            res.status(201).send({
                msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
                code: 201
            });

        } else {

            // MARK: Server response
            res.status(404).send({
                msg: `Order N°${number} not created`,
                code: 404
            });

        }

    } catch (e) {
        print(e)
        return
    }

})

// C.Read.U.D


// C.R.Update.D


// C.R.U.Delete



module.exports = router;
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.