如果你的mongodb数据库使用了验证数据库,需要加上authSource:‘验证的数据库’,mongodb默认的验证数据库为admin

const mongoose = require('mongoose');
async function main(){
    //连接mongodb数据库的test库
    await mongoose.connect('mongodb://user:password@127.0.0.1:27017/test', {
        authSource: 'admin', // 指定认证数据库
    });
}
main().then(res=>{
    console.log('mongodb连接成功')
}).catch(err=>{
    console.log('mongodb连接失败')
})

注意:如果是连接本地,不能写localhost,要写127.0.0.1!如果有用的话记得给我点赞哦!😊

Logo

鸿蒙生态一站式服务平台。

更多推荐