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.

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 webpackBundle = require('../webpack.config.js');
const webpackBundleForTest = Object.assign({}, webpackBundle, {
  output: Object.assign({}, webpackBundle.output, { path: `${__dirname}/files` })
webpack(webpackBundleForTest, utils.tick(function(bundleBuildError, bundleBuildStats) {
  assert.deepEqual(bundleBuildStats.compilation.errors, []);

  // Avoid expressions in `require()` because that scares webpack (gh-6705)
    find(msg => msg.toString().startsWith('ModuleDependencyWarning:')));

  const bundleContent = fs.readFileSync(`${__dirname}/files/dist/browser.umd.js`, 'utf8');

  acorn.parse(bundleContent, { ecmaVersion: 5 });

  const baseConfig = require('../webpack.base.config.js');
  const config = Object.assign({}, baseConfig, {
    entry: ['./test/files/sample.js'],