Get the _id of inserted document in Mongo database in NodeJS

前端 未结 10 2003
半阙折子戏
半阙折子戏 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    

提交回复
热议问题