簡體   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