- Import the mongoose module:
const mongoose = require('mongoose');
- Connect to the MongoDB database:
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true });
- Create a connection to the database:
const db = mongoose.connection;
- Handle the connection events:
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// Connected to the database
});
- Define a schema for your data:
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});
- Create a model based on the schema:
const User = mongoose.model('User', userSchema);
- Create a new instance of the model:
const newUser = new User({
name: 'John',
age: 25,
email: '[email protected]'
});
- Save the new user to the database:
newUser.save(function(err, user) {
if (err) return console.error(err);
console.log(user.name + ' saved to database.');
});
- Query the database to retrieve data:
User.find(function(err, users) {
if (err) return console.error(err);
console.log(users);
});
- Close the database connection when done:
db.close();