如何在Express和Mongo DB中使用异步等待

时间:2019-07-27 19:39:14

标签: express

    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const mongodb = require('mongodb');

    const app = express();
    app.use(cors())
    app.use(bodyParser.json());


    const MongoClient = mongodb.MongoClient;
    const url = "mongodb://localhost:27017/recart";


    app.post("/register" , (req, res) => {
        const { displayName, email, password } = req.body;
        if (!email || !displayName || !password) {
            return {code: 400, msg: "incorrect form submission"}
        }
        let insertedid = null
        MongoClient.connect(url, (err, db) => {
            if (err) throw err;
            var dbo = db.db("recart");
            var myobj = { displayName: displayName, email: email, password: password };
            dbo.collection("customers").insertOne(myobj)
            .then(res => {
                insertedid = res.insertedId
            })
        });
        res.json({id: insertedid})
    })

    app.listen(process.env.PORT || 3000, ()=> {
        console.log(`App is running on port 3000`);
    })

在这里,我将数据存储在db中并发送最后插入的id 到前端。

但id为空

我如何使用异步等待来解决此问题,

请看看

1 个答案:

答案 0 :(得分:1)

您可以使用import os, shutil from random import sample rootdir = '/Autoupload' output_dir = '/Public' for subdir, dir, files in os.walk(rootdir): for to_copy in sample(files, min(len(files), 3)): # <- at most 3 files from each dear shutil.move(os.path.join(subdir, to_copy), os.path.join(output_dir, to_copy)) 来修改帖子功能,如下所示:

async await