简体   繁体   中英

Node Can't connect to mongodb using mongoose

So I'm on a macbook running mongodb locally. Mongodb is listening on port 27017 and I can see it saying it's ready to accept connections. If I open a mongo shell, I can see it shows the connection. When I run "node index.js", the program just hangs and doesn't show and error or it doesn't show connected. Also, in the mongo server tab I can see connections accepted

Here's my code:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');


//create application
var app = express();


//add middleware
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Overrise'));

mongoose.connect('mongodb://localhost:27017/boost', function(err) {
   if (err) {
        console.log(err);

   }else{
        console.log("Connected");
  }
});

try this

mongoose.connect('mongodb://localhost:27017/boost', {useMongoClient:true});

mongoose.connection.once('open',function () {
    console.log('Connected');
}).on('error',function (error) {
    console.log('CONNECTION ERROR:',error);
});

There wasn't really anything wrong. I solved it by just doing and then writing my code later.

mongoose.connect('mongodb://localhost/boost');
var db = mongoose.connection;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM