111

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

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

_id挿入されたオブジェクトを取得するにはどうすればよいですか?

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

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

4

11 に答える 11

95

のコールバックに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
});
于 2013-01-23T14:29:18.627 に答える
90

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

試す:

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

コンソールをチェックして、私が何を意味するかを確認してください。

于 2013-01-23T14:13:26.930 に答える
21

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

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

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

于 2017-02-24T21:45:58.510 に答える
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
       }
});
于 2015-06-19T00:19:04.713 に答える
8

「_id」を取得したい場合は、simpleyを使用してください

result.insertedId.toString() 

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

于 2019-01-15T18:27:36.223 に答える
7

Mongoは完全なドキュメントをcallbackobjectとして送信するため、そこからのみ取得できます。

例えば

collection.save(function(err,room){
  var newRoomId = room._id;
  });
于 2014-09-02T05:25:01.933 に答える
7

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

于 2016-07-28T08:34:22.877 に答える
5

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

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

  await db.collection('users').insertOne(data)

  return data
}

データを返します:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}
于 2019-11-04T09:45:29.377 に答える
2

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

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });
于 2018-11-16T08:05:44.137 に答える
1

他の応答と同様に、非同期待機、es6+機能を使用して変数を取得できます。

const insertData = async (data) => {

  const { ops } = await db.collection('collection').insertOne(data)
  console.log(ops[0]._id)
  
}

于 2021-03-03T18:01:25.623 に答える
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;
于 2020-06-22T14:18:58.560 に答える