nodejs连接mongodb

2022/4/4 19:21:07

本文主要是介绍nodejs连接mongodb,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

/*
 * @Description: 
 * @Author: NanKe
 * @Date: 2022-03-30 22:01:24
 * @LastEditTime: 2022-04-04 11:46:12
 * @LastEditors: NanKe
 * @Cnblogs: https://www.cnblogs.com/NanKe-Studying/
 * @FilePath: \cloud-teach-aide\server\database\db.js
 */

const mongoose = require('mongoose')
const options = {
    db_user: "",
    db_pwd: "",
    db_host: "localhost",
    db_port: 27017,
    db_name: "",
    authSource:"admin"
};

const DB_URL = "mongodb://" + options.db_user + ":" + options.db_pwd + "@" + options.db_host + ":" + options.db_port + "/" + options.db_name + "?authSource=" +options.authSource;
// const DB_URL = 'mongodb://用户名:密码@localhost:27017/数据库名?authSource=admin'
// const DB_URL = 'mongodb://localhost:27017/cloud-teach-aide'
mongoose.connect(DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

mongoose.connection.on('connected', () => {
    console.log('Mongoose连接成功:' + DB_URL);
});

mongoose.connection.on('error', (err) => {
    console.log('Mongoose连接出错:' + err);
});

mongoose.connection.on('disconnected', () => {
    console.log('Mongoose断开连接');
});

要加authSource



这篇关于nodejs连接mongodb的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程