在 nodejs 和 mongodb 中连接数据库之前未定义
undefined before the database is connected in nodejs and mongodb
我创建了一个应用程序,我想要实现的是当应用程序运行时,从 table user
中获取 uid
并将其插入到新的 table msg
,代码如下。
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)
}
但是运行起来,打印日志的显示顺序是
undefined
mongodb connected
uid
是 undefined
,因为数据库还没有连接,如何解决这个问题?谢谢。
您需要确保您的数据库查询本质上是 async
。
如果您正在使用async/await
,您可以
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});
你也可以用then/catch
db.collection("user").findOne({name: to}).then(userinfo => {
let uid = userinfo.uid;
}
我创建了一个应用程序,我想要实现的是当应用程序运行时,从 table user
中获取 uid
并将其插入到新的 table msg
,代码如下。
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)
}
但是运行起来,打印日志的显示顺序是
undefined
mongodb connected
uid
是 undefined
,因为数据库还没有连接,如何解决这个问题?谢谢。
您需要确保您的数据库查询本质上是 async
。
如果您正在使用async/await
,您可以
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});
你也可以用then/catch
db.collection("user").findOne({name: to}).then(userinfo => {
let uid = userinfo.uid;
}