美文网首页Web前端之路Web 前端开发
MongoDB 服务起来了,终端可以使用 shell 可以查询,

MongoDB 服务起来了,终端可以使用 shell 可以查询,

作者: 梁同桌 | 来源:发表于2017-05-27 23:39 被阅读837次

    MongoDB 服务起来了,终端可以使用 shell 可以查询,但是 Node 始终连结不上?

    Node代码如下

    
    const mongoose = require('mongoose');
    const db = mongoose.connect('mongodb://localhost:27017/test');
    db.Promise = global.Promise;
    
    db.connection.on('error', function(error) {
        console.log('___db:error');
        console.log(error);
    });
    
    db.connection.on('open', function() {
        console.log('___db:open');
    });
    
    

    打印的错误堆栈信息

    
    ___db:error
    { MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: getaddrinfo ENOTFOUND localhost localhost:27017]
        at Pool.eventHandler (/Users/liangyabin/Desktop/写一些小demo/node_modules/mongodb-core/lib/topologies/server.js:328:35)
        at emitOne (events.js:96:13)
        at Pool.emit (events.js:191:7)
        at Connection.<anonymous> (/Users/liangyabin/Desktop/写一些小demo/node_modules/mongodb-core/lib/connection/pool.js:274:12)
        at Object.onceWrapper (events.js:293:19)
        at emitTwo (events.js:106:13)
        at Connection.emit (events.js:194:7)
        at Socket.errorHandler (/Users/liangyabin/Desktop/写一些小demo/node_modules/mongodb-core/lib/connection/connection.js:177:49)
        at Object.onceWrapper (events.js:293:19)
        at emitOne (events.js:96:13)
        at Socket.emit (events.js:191:7)
        at connectErrorNT (net.js:1034:8)
        
    

    浏览器访问:http://localhost:27017

    显示:It looks like you are trying to access MongoDB over HTTP on the native driver port.

    哪里出问题了?

    说出来大家可能不信

    const db = mongoose.connect('mongodb://localhost:27017/test');
    改成
    const db = mongoose.connect('mongodb://127.0.0.1:27017/test');
    这样就不会报错了,我的天啊
    

    最后确定是 hosts 文件的问题

    相关文章

      网友评论

        本文标题:MongoDB 服务起来了,终端可以使用 shell 可以查询,

        本文链接:https://www.haomeiwen.com/subject/djdcfxtx.html