I create mongoose.js model:
db = mongoose.createConnection(mongoUrl)
model = db.model('Model', schema)
can I get mongoUrl (or server and DB name) from model?
Create Mongoose Model. 1 Create Employee.js File. So, first inside the server folder, create a new folder named models. Now inside the model’s folder, create a new file call ... 2 Create Employee Schema. 3 Export Mongoose Model. 4 Import Mongoose Model.
Load mongoose and express by adding the following code to server.js. Then connect to a local MongoDB instance using the mongoose.connect () function. We pass the useNewUrlParser: true, etc. to mongoose.connect () to avoid the DeprecationWarning.
Many Node.js developers choose to work with Mongoose to help with data modeling, schema enforcement, model validation, and general data manipulation. And Mongoose makes these tasks effortless.
This callback function, in turn, has two parameters – request and response. This is how a GET request is made in mongoose. But currently, this will do nothing. We have to specify a method to fetch the data from the database. There are several methods. We will use the most common one, the find () method.
Yeah, you can reference the original DB connection through model.db
. So you can get all the connection information you need like this:
console.log(model.db.host); // localhost
console.log(model.db.port); // 27017
console.log(model.db.name); // myDatabase
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