首页 > 解决方案 > NodeJS猫鼬连接问题

问题描述

我是 NodeJS 的新手,今天开始了 MongoDb 部分。我观看 NodeJS 视频(录制于 2016 年),它们与猫鼬连接。但它对我不起作用。

代码:

    var mongoose = require('mongoose');

    mongoose.Promise = require('bluebird');

    var mongoDB = "mongodb://localhost/nodedb";

    mongoose.connect(mongoDB,{ useNewUrlParser: true } ,function(err,err){
        if(err){
            console.log("Cant connect");
        }else{
            console.log("Connected to :" + mongoDB);
        }
    })

使用这种方法,我可以连接。至少出现在 Console 中:

Connected to :mongodb://localhost/nodedb

但是有一些错误,其中之一是:

Unhandled rejection MongoError: port must be specified

我写 mongodb://localhost:27017/nodedb 。但是现在连不上。问题在哪里?

标签: node.js

解决方案


需要指定mongodb端口,默认27017

https://docs.mongodb.com/manual/reference/default-mongodb-port/

我像这样使用猫鼬:

   mongoose.connect('mongodb://localhost:27017/somename')
    .then((db)=>{console.log(`connected`);})
    .catch(error=>console.log(error));

推荐阅读