解决:如果有人感兴趣,似乎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和Node10。
编辑:没有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': 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] ] ] }
答案 0 :(得分:3)
尝试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]
答案 1 :(得分:3)
我也有Windows。一旦安装了Mongo,它便会在后台运行,并且很好,否则,您每次都必须手动启动一个mongod
实例。
即使现在支持then/catch
,我还是更喜欢使用try/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
文档
答案 2 :(得分:2)
我不确定。但我认为您应该执行该功能。 等待initDD()。 只需很少的代码即可了解发生的情况。
类似的东西
// 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();
用'mongodb:// localhost:27017 / local'替换process.env.DATABASE_SERVER