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] ] ] }
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With