mongoose setup

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