How is it possible to call multiple functions on the mongoose
variable? Shouldn't moogoose
be called repeatedly and invoked on appropriately?
//Import
const express = require("express");
const mongoose = require("mongoose");
//initialize a variable called app to express
const app = express();
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
// Connect to MongoDB
mongoose.connect(db)
mongoose.then(() => console.log("MongoDB connected"))
mongoose.catch(err => console.log(err));
Connecting to mongoose returns a promise (the connect()
function). You need to wait for this to resolve before you can proceed. That's the reason why you chain .then
on the connect()
function and not on the mongoose variable since the mongoose variable itself is not a promise. The bottom piece of code doesn't wait for the connection to occur at all and doesn't call .then
on a promise.
If you are confused on what the .then
and .catch
functions do exactly read more about promises here: Promise and Promise chaining (MDN)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.