Home > OS >  undefined before the database is connected in nodejs and mongodb
undefined before the database is connected in nodejs and mongodb

Time:04-29

I created an app, what I want to achieve is when the app runs, get the uid from the table user and insert it into a new table msg, code like following.

conn.js

'use strict'
const { MongoClient } = require('mongodb');
const client = new MongoClient(dbUrl, { useNewUrlParser: true });
client.connect(function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('mongodb connected');
    }
});
const db = client.db(dbName);
module.exports = db;

app.js

'use strict';
const db = require('./conn');
try {
    let to = "nick";
    let from = "susan";
    let content = "test";

    let userinfo = db.collection("user").findOne({name: to});
    let uid = userinfo.uid;
    console.log(uid)
    
    db.collection("msg").insertOne({from: from, to: to})
} catch(e) {
    console.log(e)
}

But it runs, the displayed order of the printed log is

undefined
mongodb connected

uid is undefined, because database isn't connected yet, how to fix this? Thank you.

CodePudding user response:

You need to make sure your db queries are async in nature.

If you are using async/await, you can do

let userinfo = await db.collection("user").findOne({name: to});
let uid = userinfo.uid;
console.log(uid);
    
await db.collection("msg").insertOne({from: from, to: to});

You can also use then/catch as well

db.collection("user").findOne({name: to}).then(userinfo => {
 let uid = userinfo.uid;
}
  • Related