Connect to MongoDB Using Mongoose
suggest changeFirst, install Mongoose with:
npm install mongoose
Then require it from server.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
Next, create the database schema and the name of the collection:
var schemaName = new Schema({
request: String,
time: Number
}, {
collection: 'collectionName'
});
Create a model and connect to the database:
var Model = mongoose.model('Model', schemaName);
// connect() returns a promise (Mongoose 6+). A failure rejects that promise.
mongoose.connect('mongodb://localhost:27017/dbName');
Next, start MongoDB and run server.js using node server.js
To check if we have successfully connected to the database, we can use the events open, error from the mongoose.connection object.
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents