Get the _id of inserted document in Mongo database in NodeJS

前端 未结 10 1920
半阙折子戏
半阙折子戏 2020-11-27 02:53

I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:

// ...
collection.         


        
相关标签:
10条回答
  • 2020-11-27 03:25

    Now you can use insertOne method and in promise's result.insertedId

    0 讨论(0)
  • 2020-11-27 03:31

    if you want to take "_id" use simpley

    result.insertedId.toString() 
    

    // toString will convert from hex

    0 讨论(0)
  • 2020-11-27 03:32

    I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's 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
           }
    });
    
    0 讨论(0)
  • 2020-11-27 03:34

    Another way to do it in async function :

    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;
    
    0 讨论(0)
  • 2020-11-27 03:35

    You could use async functions to get _id field automatically without manipulating data object:

    async function save() {
      const data = {
        name: "John"
      }
    
      await db.collection('users', data )
    
      return data
    }
    

    Returns data:

    {
      _id: '5dbff150b407cc129ab571ca',
      name: 'John'
    }
    
    0 讨论(0)
  • 2020-11-27 03:43

    A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

    The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

    collection.insert(objectToInsert, function(err){
       if (err) return;
       // Object inserted successfully.
       var objectId = objectToInsert._id; // this will return the id of object inserted
    });
    
    0 讨论(0)
提交回复
热议问题