Categories
MongoDB

Using MongoDB with Mongoose

Spread the love

To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.

In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.

Getting Started with Mongoose

We can install the package by running:

npm install mongoose --save

Then we can use it by writing:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

We connect th our MongoDB database with Mongoose by using the mongoose.connect method.

Then to see if we connected successfully, we can listen to the open event.

Defining Schemas

Now we can define a schema to restrict what we can put on our documents.

This is something that’s not available with the native MongoDB client.

For example, we can write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

We create the schema with the mongoose.Schema constructor.

The object has the fields as the keys and the data type as the values.

Then we define the model with the mongoose.model method.

Then we use the Kitten constructor, and then we call save to save the Kitten object to the database.

The _id will automatically be generated for each inserted entry.

If we want to get the entries, then we can call the find method:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find((err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

If we want to find a specific entry we can pass in an object to the first argument of find :

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function () {
  console.log(`hello ${this.name}`);
}

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'james' });
baby.speak();
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find({ name: /^james/ },(err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

If we want to add methods, we can write:

const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
  console.log('connected')
});

const kittySchema = new mongoose.Schema({
  name: String
});

kittySchema.methods.speak = function () {
  console.log(`hello ${this.name}`);
}

const Kitten = mongoose.model('Kitten', kittySchema);
const baby = new Kitten({ name: 'baby' });
baby.speak();
baby.save((err, baby) => {
  if (err) {
    return console.error(err);
  }
  console.log(baby.name);
});

Kitten.find((err, kittens) => {
  if (err) return console.error(err);
  console.log(kittens);
})

We added a method to the Kitten model by adding a method to the methods object property.

Conclusion

We can create schemas, add items, and find items with Mongoose.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *