mongodb使用mongoose没有办法链接,但是软件Robomongo和命令mongo都可以连接

问题如题。写了个小程序,突然之间就没有办法连上了,之前还可以的。
mongodb 和程序都是在本地mongodb 是用brew 安装的。网上查了好多,还是没找到原因,数据库的文件夹也重新删除过,还是不管用。求老司机指导,贴一下代码吧。

let mongoose = require("mongoose");
let utils = require("./utils");
var log4js = require('log4js');
//log the  logger messages to a file, and the console ones as well.
log4js.configure({
    appenders: [
        {
            type: "file",
            filename: "log/trace_all.log",
        },
        {
            type: "console"
        }
    ],
    replaceConsole: true
});
//regist model 
require("./models/comment");
let CommentModel = mongoose.model("Comment");

mongoose.connect("mongodb://localhost:27017/acfun");
let db = mongoose.connection;
db.once("open", () => {
    console.log("mongoose connect mongodb://localhost:27017/acfun success");
});
db.on("error", (err) => {
    console.log(`db error : ${err}`);
    setTimeout(()=>{
        mongoose.connect("mongodb://localhost:27017/acfun");
    },500);
});
阅读 4.1k
3 个回答
  1. 数据库启动了嘛?

我删掉你贴出来的代码的其它部分,只留下Mongodb相关,在我本机跑没问题呢!

let mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/acfun");
let db = mongoose.connection;
db.once("open", () => {
    console.log("mongoose connect mongodb://localhost:27017/acfun success");
});
db.on("error", (err) => {
    console.log(`db error : ${err}`);
    setTimeout(()=>{
        mongoose.connect("mongodb://localhost:27017/acfun");
    },500);
});

输出结果:

clipboard.png

所以,你大概需要考虑是其它原因了。

我的连接方法这样的...没问题

let mongoose = require('mongoose')
let conStr = 'mongodb://127.0.0.1/app'

mongoose.Promise = global.Promise

/*mongoose.set('debug', true)*/

const conn = mongoose.createConnection(conStr)

mongoose.connection.on('error', console.error.bind(console, '数据库连接错误\n'))
mongoose.connection.on('connected', console.log.bind(console, '成功连接到数据库\n\n\n'))

module.exports = conn
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题