Mongoose.connect在Mongodb未运行时未抛出任何错误。

huangapple go评论69阅读模式
英文:

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

问题

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

我有这个函数来初始化一个 Mongoose 连接:

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) // 不会进入这里...
    }

}

这个 Promise 不会被拒绝,即使我还没有启动 MongoDB 服务。我也尝试了回调版本,结果一样。明显我没有运行任何 MongoDB,但 Mongoose "连接" 就好像一切都没有问题。

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

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

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
英文:

Solved: if anybody is interested, it seems that MongoDB is just starting automatically on Windows startup...

I have this function to initialize a Mongoose connection:

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...
    }

}

This promise doesn't get rejected, even if i haven't started my MongoDB service yet. I tried also the callback version- same result. I clearly do not have any MongoDB running, and yet Mongoose "connects" as if nothing is wrong.

What could be the problem here? I have a standard MongoDB setup, latest Mongoose, Windows 7 and Node 10.

Edit: the logged value of the "db", when no MogoDB is running:

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] ] ] }

答案1

得分: 4

我也有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);
});

如果你不想对模型进行缓冲,以避免出现混乱的行为,你需要在模式或全局范围内禁用它:

参考:mongoose 文档
https://mongoosejs.com/docs/guide.html#bufferCommands
https://mongoosejs.com/docs/connections.html#buffering

英文:

I have Windows too. Once Mongo is installed it runs in the background and it's fine, otherwise you'd have to start manually a mongod instance each time.

I prefer to use then/catch even if try/catch is now supported:

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);
	});

If you don't want to buffer your models, thus getting confusing behaviour, you need to disable it either on your schema or globally:

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

reference: mongoose docs

答案2

得分: 3

I'm not sure. but I think you should execute the function.
await initDD ().
It is little code to understand what happens.

something like that

//database.js

const mongoose = require("mongoose");
async function connect() {
  await mongoose.connect('mongodb://localhost:27017/local', {
    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() {
  // database connection
  await connect();
  // start server
  const port = process.env.PORT || 4000;
  await app.listen(port, () => console.log(`Server on port ${port} `));
}
main();
英文:

I'm not sure. but I think you should execute the function.
await initDD ().
It is little code to understand what happens.

something like that

//database.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();

replace process.env.DATABASE_SERVER, with 'mongodb://localhost:27017/local'

答案3

得分: 1

尝试使用MongoClient.connect

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

错误信息 -

错误信息 ->MongoNetworkError: 在首次连接时无法连接到服务器 [localhost:27017] [MongoNetworkError: 连接 ECONNREFUSED 127.0.0.1:27017]
英文:

Try 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 -

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

huangapple
  • 本文由 发表于 2020年1月3日 20:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定