Skip to content

Commit

Permalink
solved issue: export func returned run func(),not promise
Browse files Browse the repository at this point in the history
  • Loading branch information
effy971 committed Oct 14, 2020
1 parent 779255e commit b72031c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 20 deletions.
19 changes: 13 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ const express = require("express");
const insertDb = require("./insertdb");
require("dotenv").config();

const DB_URL = process.env.DB_CREDENTIALS;

app = express();
app.use(
express.urlencoded({
Expand All @@ -16,10 +14,19 @@ app.get("/", (req, res) => {
res.send("you are at backend root");
});

app.post("/register", (req, res) => {
console.log(req.body);
insertDb(req.body.name, req.body.email, req.body.password);
res.send("registration recived!");
app.post("/register", async (req, res) => {
try {
const result = await insertDb(
req.body.name,
req.body.email,
req.body.password
).catch(console.dir);
if (result) {
res.send("registration success!");
} else {
res.send("registration failed");
}
} catch (error) {}
});

app.listen(PORT, (req, res) => {
Expand Down
30 changes: 16 additions & 14 deletions insertdb.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,28 @@
const { MongoClient } = require("mongodb");

module.exports = function (name, email, password) {
module.exports = async function (name, email, password) {
const uri = process.env.DB_CREDENTIALS;

const client = new MongoClient(uri);
let successOrFail = false;
try {
await client.connect();

async function run() {
try {
await client.connect();
const database = client.db("4learn");
const collection = database.collection("userReg");

const database = client.db("4learn");
const collection = database.collection("userReg");
// create js obj received by /register

// create js obj received by /register
const doc = { name: name, email: email, password: password };
const result = await collection.insertOne(doc);

const doc = { name: name, email: email, password: password };
const result = await collection.insertOne(doc);

console.log(`${result.insertedCount} documents were inserted into db`);
} finally {
await client.close();
console.log(`${result.insertedCount} documents were inserted into db`);
console.log(result.insertedCount > 0);
if (result.insertedCount > 0) {
successOrFail = true;
return true;
}
} finally {
await client.close();
}
run().catch(console.dir);
};

0 comments on commit b72031c

Please sign in to comment.