在数据库连接到Nodejs和MongoDB之前,未定义
我创建了一个应用程序,我想实现的是,当应用程序运行时,从表user
中获取uid
,然后将其插入新表格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
,因为数据库尚未连接,所以如何解决此问题?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要确保您的数据库查询本质上是
ynnc
。如果您使用的是
async/等待
,则可以使用
,然后/catch
You need to make sure your db queries are
async
in nature.If you are using
async/await
, you can doYou can also use
then/catch
as well