数据库
首页 > 数据库> > nodejs连接mongodb

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

标签:const,nodejs,mongodb,DB,db,连接,mongoose,authSource,options
来源: https://www.cnblogs.com/NanKe-Studying/p/16098737.html