Categories
MongoDB

Using MongoDB with Mongoose — SchemaTypes

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.

SchemaType

A SchemaType is a configuration object for an individual property.

For example, 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
});
console.log(kittySchema.path('name') instanceof mongoose.SchemaType);

to check that the name field in the kittySchema is an instance of mongoose.SchemaType .

It should return true , so we know that name is a SchemaType .

If we have nested fields in a schema, we also have to set the types for the nested fields:

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: { type: String },
  nested: {
    firstName: { type: String },
    lastName: { type: String }
  }
});

Schema Types

With Mongoose, we can define a few schema types with our field.

They include:

  • required: boolean or function, if true adds a required validator for this property
  • default: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
  • select: boolean, specifies default projections for queries
  • validate: function, adds a validator function for this property
  • get: function, defines a custom getter for this property using Object.defineProperty().
  • set: function, defines a custom setter for this property using Object.defineProperty().
  • alias: string, available with Mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this path.
  • immutable: boolean, defines path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has isNew: true.
  • transform: function, Mongoose calls this function when you call Document#toJSON() function, including when you JSON.stringify() a document.

For example, 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 schema = new mongoose.Schema({
  integerOnly: {
    type: Number,
    get: v => Math.round(v),
    set: v => Math.round(v),
    alias: 'i'
  }
});

to create a schema with the integerOnly field.

We control how the value is get and set with the get and set methods respectively.

And we added an alias property to define another name we can access it with.

Indexes

We can add indexes for fields. For example, 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 schema = new mongoose.Schema({
  test: {
    type: String,
    index: true,
    unique: true
  }
});

to add the test schema with the index property set to true to add an index for the test field.

The unique property set to true will add a unique index.

Conclusion

We can specify different schema types to set the fields for the schema.

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 *