Mongoose never connects to mongodb

2019-02-23 03:13发布

I'm trying to connect to MongoDB using Mongoose on an Amazon EC2 Linux server.

Here's my code:

var mongoose = require('mongoose');
console.log("Attempting antyhing to do with mongoose"); //shown

var db = mongoose.connection;
db.on('error',console.error.bind(console,'db connection error:')); //not shown
db.once('open',function(){
    console.log("Successful connection to db!"); //not shown
});

mongoose.connect('mongodb://localhost:27017/local',function(err){
    console.log("some kinda connection made"); //not shown
    if(err)
    {
        console.log("err: "+err);
    }
});

Frustratingly, I'm not getting any errors from mongoose whatsoever, but nothing seems to show up.

There seem to be a lot of questions about no callback with mongoose and mongo.

Here's a couple that I've looked at that I don't think are the problem for me:

Also for reference I'm following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

One thing I am doing that I'm worried about is I've split my code up into multiple files. So this mongoose connection code is being called from a app/models/host.js (or bear.js in tutorial) file. Let me know if posting the other files would be helpful.

2条回答
我想做一个坏孩纸
2楼-- · 2019-02-23 03:37

Haven't really solved the problem but I found a work-around... not using mongoose. Would still appreciate connecting to mongoose, especially as I was trying to follow a tutorial.

Here's my code that successfully connects to mongodb:

var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017/host";

//Go Ahead and connect & sketchily initialize the db
var db;
var collection;
MongoClient.connect(url,function(err,database){
    if(err){
        console.log("Coudln't connect to mongo. Error"+err);
    } else{
        db = database;
        collection = db.collection('hosts');
        console.log("Connected to mongo, db good to go");
    }
});
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-23 03:46

I also faced the same issue.

Check that the Mongoose version you are using supports the MongoDb server version

Check compatibility on this link: http://mongoosejs.com/docs/compatibility.html

Change the version of Mongoose in package.json file accordingly.

Hope this helps!

查看更多
登录 后发表回答