浏览器中的 Mongoose

¥Mongoose in the Browser

Mongoose 支持在浏览器中创建结构和验证文档。Mongoose 的浏览器库不支持保存文档、queriespopulatediscriminators 或除模式和验证文档之外的任何其他 Mongoose 功能。

¥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.

Mongoose 有一个预构建的浏览器库包。如果你将代码与 Webpack 打包在一起,并且你的 Webpack target'web',则应该能够导入 Mongoose 的浏览器库,如下所示:

¥Mongoose has a pre-built bundle of the browser library. If you're bundling your code with Webpack, you should be able to import Mongoose's browser library as shown below if your Webpack target is 'web':

import mongoose from 'mongoose';

你可以使用以下语法从 Node.js 访问 Mongoose 浏览器库:

¥You can use the below syntax to access the Mongoose browser library from Node.js:

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

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

使用浏览器库

¥Using the Browser Library

Mongoose 的浏览器库非常有限。它支持的唯一用例是验证文档,如下所示。

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

import mongoose from 'mongoose';

// 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());