MongoDB - Node Driver

There are two libraries to use MongoDB in Node.js:

We will only cover mongoose. To install it:

$ npm install mongoose

And, to connect to your database:

const mongoose = require('mongoose');

// connect, settings from the documentation
await mongoose.connect('mongodb://xxx', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
});

Basic usage

Mongoose is an Object-Document Mapping (ODM) library. It means we'll abstract the database as a JSON Schema, and mongoose will act as a bridge between objects (JavaScript) and documents (MongoDB).

Schema

A schema is the abstraction of the database.

const UsersSchema = new Schema({
    name: {
        type: String,
        minLength: 2,
        maxLength: 128,
        trim: true,
        default: 'John doe'
    },
    // embedded document/sub-document
    cars: [
        {
            model: {
                type: String,
                required: true
            }
        }
    ]
})

Model

From a schema, we can instantiate a model from which you can call methods with the same arguments as in the MongoDB course.

const UsersModel = mongoose.model('Users', Users);
await UsersModel.find(...);
await UsersModel.findOne(...);
await UsersModel.updateOne(...);
await UsersModel.updateMany(...);
await UsersModel.insertOne(...);
await UsersModel.insertMany(...);

🧼 Don't forget to catch and handle exceptions.

πŸ”₯ You can't access attributes that are not in your model, even if you can see them with console.log.

✍️ Some useful methods when dealing with ObjectID:

// generate an ObjectID
new mongoose.Types.ObjectId();
// cast from string to ObjectID
mongoose.Types.ObjectId("id");
// verify that an ID is valid
mongoose.Types.ObjectId.isValid("id")