繁体   English   中英

Mongoose.connect 不抛出任何错误,当 Mongodb 未运行时

[英]Mongoose.connect not throwing any error, when Mongodb is not running

解决:如果有人感兴趣,似乎MongoDB只是在Windows启动时自动启动......

我有这个函数来初始化猫鼬连接:

const mongoose = require('mongoose');

let db;

async function initDD(){
    try {
       db  = await  mongoose.connect('mongodb://localhost:27017/local', { useNewUrlParser: true });   

    } catch (error) {
        console.log('mongoose error',error)//Doesn't come to this...
    }

}

这个承诺不会被拒绝,即使我还没有开始我的 MongoDB 服务。 我也尝试了回调版本-相同的结果。 我显然没有运行任何 MongoDB,但 Mongoose “连接”,好像没有任何问题。

这里可能有什么问题? 我有一个标准的 MongoDB 设置、最新的 Mongoose、Windows 7 和 Node 10。

编辑:“db”的记录值,当没有 MogoDB 运行时:

Mongoose {
  connections:
   [ NativeConnection {
       base: [Circular],
       collections: [Object],
       models: [Object],
       config: [Object],
       replica: false,
       options: null,
       otherDbs: [],
       relatedDbs: {},
       states: [Object],
       _readyState: 1,
       _closeCalled: false,
       _hasOpened: true,
       plugins: [],
       _listening: false,
       _connectionOptions: [Object],
       name: 'local',
       host: 'localhost',
       port: 27017,
       user: undefined,
       pass: undefined,
       client: [MongoClient],
       '$initialConnection': [Promise],
       db: [Db] } ],
  models: { User: Model { User } },
  modelSchemas:
   { User:
      Schema {
        obj: [Object],
        paths: [Object],
        aliases: {},
        subpaths: {},
        virtuals: [Object],
        singleNestedPaths: {},
        nested: {},
        inherits: {},
        callQueue: [],
        _indexes: [],
        methods: {},
        methodOptions: {},
        statics: {},
        tree: [Object],
        query: {},
        childSchemas: [],
        plugins: [Array],
        '$id': 1,
        s: [Object],
        _userProvidedOptions: {},
        options: [Object],
        '$globalPluginsApplied': true } },
  options: { pluralization: true, [Symbol(mongoose:default)]: true },
  _pluralize: [Function: pluralize],
  Schema:
   { [Function: Schema]
     reserved:
      [Object: null prototype] {
        populated: 1,
        remove: 1,
        validate: 1,
        toObject: 1,
        schema: 1,
        save: 1,
        modelName: 1,
        get: 1,
        isNew: 1,
        isModified: 1,
        init: 1,
        errors: 1,
        db: 1,
        collection: 1,
        removeListener: 1,
        listeners: 1,
        once: 1,
        on: 1,
        emit: 1,
        prototype: 1 },
     Types:
      { String: [Function],
        Number: [Function],
        Boolean: [Function],
        DocumentArray: [Function],
        Embedded: [Function: SingleNestedPath],
        Array: [Function],
        Buffer: [Function],
        Date: [Function],
        ObjectId: [Function],
        Mixed: [Function],
        Decimal: [Function],
        Decimal128: [Function],
        Map: [Function: Map],
        Oid: [Function],
        Object: [Function],
        Bool: [Function],
        ObjectID: [Function] },
     ObjectId:
      { [Function: ObjectId]
        schemaName: 'ObjectId',
        get: [Function],
        _checkRequired: [Function],
        _cast: [Function: castObjectId],
        cast: [Function: cast],
        checkRequired: [Function] } },
  model: [Function],
  plugins:
   [ [ [Function], [Object] ],
     [ [Function], [Object] ],
     [ [Function], [Object] ],
     [ [Function], [Object] ] ] }

我也有Windows。 安装 Mongo 后,它会在后台运行并且很好,否则您每次都必须手动启动一个mongod实例。

即使现在支持try/catch我也更喜欢使用then/catch

mongoose.connect(
        'mongodb://localhost:27017/test',{
            useNewUrlParser: true,
            useCreateIndex: true,
            useFindAndModify: false,
            useUnifiedTopology: true
        }
    )
    .then(() => console.log('DB Connection Successfull'))
    .catch((err) => {
        console.error(err);
    });

如果你不想缓冲你的模型,从而导致混乱的行为,你需要在你的架构上或全局禁用它:

https://mongoosejs.com/docs/guide.html#bufferCommands https://mongoosejs.com/docs/connections.html#buffering

参考: mongoose文档

我不知道。 但我认为您应该执行该功能。 等待initDD()。 只需少量代码即可了解会发生什么。

类似的东西

//数据库.js

const mongoose = require("mongoose");
  async function connect() {
  await mongoose.connect(process.env.DATABASE_SERVER, {
   useNewUrlParser: true
  });
  if (mongoose.connection.readyState === 1) {
   console.log("Successfully connected to database");
  }
 }
module.exports = { connect };

// index.js

const app = require("./app");
const { connect } = require("./database");
async function main() {
 // dayabase conexion
 await connect();
 // start server
 const port = process.env.PORT || 4000;
 await app.listen(port, () => console.log(`Server on port ${port} `));
}
main();

用'mongodb://localhost:27017/local'替换process.env.DATABASE_SERVER

试试 MongoClient.connect

async function initDD() {
  try {
    await MongoClient.connect("mongodb://localhost:27017/test", {
      useNewUrlParser: true
    });
  } catch (error) {
    console.log("error is ->" + error);
  }
}
initDD();

错误是——

error is ->MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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