在数据库连接到Nodejs和MongoDB之前,未定义

发布于 2025-01-25 07:46:20 字数 992 浏览 3 评论 0原文

我创建了一个应用程序,我想实现的是,当应用程序运行时,从表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

uidundefined,因为数据库尚未连接,所以如何解决此问题?谢谢。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下客 2025-02-01 07:46:20

您需要确保您的数据库查询本质上是ynnc

如果您使用的是async/等待,则可以

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});

使用,然后/catch

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文