Mongoose in the Browser

Mongoose supports creating schemas and validating documents in the browser. Mongoose's browser library does not support saving documents, queries, populate, discriminators, or any other Mongoose feature other than schemas and validating documents.

Use the below syntax to access the Mongoose browser library.

// Using `require()`
const mongoose = require('mongoose/browser');

// Using ES6 imports
import mongoose from 'mongoose/browser';

Using the Browser Library

Mongoose's browser library is very limited. The only use case it supports is validating documents as shown below.

import mongoose from 'mongoose/browser';

// Mongoose's browser library does **not** have models. It only supports
// schemas and documents. The primary use case is validating documents
// against Mongoose schemas.
const doc = new mongoose.Document({}, new mongoose.Schema({
  name: { type: String, required: true }
}));
// Prints an error because `name` is required.
console.log(doc.validateSync());

Building With Webpack

Mongoose uses ES2015 (also known as ES6) syntax, so in order to use Mongoose with older browsers you'll need to use a tool like Babel. As of version 5.x, Mongoose no longer has an officially supported pre-built browser bundle, you need to compile the browser library yourself.

To build Mongoose's browser library using Webpack, you'll need to use babel-loader. Because of how Webpack loads require() statements, it pulls in a lot of built-in Node.js modules. In order to avoid this, you need to use the node Webpack config option as shown below.

// Below is the Webpack config Mongoose uses for testing
const config = {
  entry: ['./test/files/sample.js'],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/i,
        loader: 'babel-loader'
      }
    ]
  },
  node: {
    // Replace these Node.js native modules with empty objects, Mongoose's
    // browser library does not use them.
    // See https://webpack.js.org/configuration/node/
    dns: 'empty',
    fs: 'empty',
    'module': 'empty',
    net: 'empty',
    tls: 'empty'
  },
  target: 'web'
};
Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#