粘贴一份打算存进 MongoDB 的文档,就能得到一个 CommonJS 格式的 Mongoose schema 文件:用 new Schema({...}) 定义字段,用 mongoose.model() 注册模型,末尾是 module.exports。保存到 Express 项目的 models/ 文件夹中,直接 require 即可。
字段路径完全保留 JSON key 的原样,所以 schema 无需任何改名就能读取集合中已有的文档。粘贴文档数组时,所有文档的 key 会合并到同一个 schema 中。
mongoexport 输出也可以。模型名(默认 MyModel)。可以带空格:blog comment 会变成 BlogComment。models/Comment.js 之类的文件,在路由中用 const Comment = require('./models/Comment') 加载。[
{ "author": "mina", "body": "Great post!", "likes": 3, "approved": true, "posted_at": "2024-05-01T09:30:00Z" },
{ "author": "leo", "body": "Typo in step 2", "likes": 0, "approved": false, "posted_at": "2024-05-02T11:00:00Z", "reply_to": "6634a1" }
]const mongoose = require('mongoose');
const { Schema } = mongoose;
const commentSchema = new Schema({
_id: { type: Schema.Types.ObjectId, auto: true },
author: { type: Schema.Types.String, required: true },
body: { type: Schema.Types.String, required: true },
likes: { type: Schema.Types.Number, required: true },
approved: { type: Schema.Types.Boolean, required: true },
posted_at: { type: Schema.Types.Date, required: true },
reply_to: { type: Schema.Types.String }
});
const Comment = mongoose.model('Comment', commentSchema);
module.exports = Comment;reply_to 只出现在第二条评论中,所以生成时不带 required;ISO 日期字符串 posted_at 变成 Schema.Types.Date。两者都保留 snake_case 名称,因为 schema 路径必须与存储的 key 一致。
Schema.Types.Number,true/false → Schema.Types.Boolean,2024-05-01 或 2024-05-01T09:30:00Z 这样的 ISO 8601 字符串 → Schema.Types.Date,其他字符串 → Schema.Types.String。"01234" 这样带引号的数字仍是 String,邮编和电话号码开头的零得以保留。Schema.Types.Mixed;同一种基本类型值组成的数组变成 [Schema.Types.String] 这样的类型化数组,其他情况为 [Schema.Types.Mixed]。required: true。数组永远不会加,因为 Mongoose 会用 [] 填充缺失的数组。_id key 会被去掉;schema 改为声明 _id: { type: Schema.Types.ObjectId, auto: true }。home-url 这类不是合法 JavaScript 标识符的 key 会写成带引号的 key。如果已经和前端约定好了请求体,把那份 JSON 变成 schema 草稿,直接接到 POST 路由里的 Comment.create(req.body) 上。
从用 strict: false 或原生驱动填充的集合中取出几个文档。哪些字段总是存在、哪些只是偶尔出现,会立刻通过有无 required 体现出来。
mongoose.model('Comment', ...) 注册,Mongoose 会把这个名称转成小写复数来确定集合:comments。如果现有集合用的是别的名称,请传入第三个参数。Mixed 字段的原地修改不会被追踪;修改嵌套值后,请在 save() 之前调用 doc.markModified('profile'),或者把该字段换成子 schema。unique 约束。请给用于查询的字段加上 unique: true 或 index: true。import / export default)吗?本页只生成使用 require 和 module.exports 的 CommonJS。在 "type": "module" 的项目中,把前两行改成 import mongoose, { Schema } from 'mongoose',最后一行改成 export default Comment。TypeScript 或 NestJS 请改用 JSON → Mongoose (TS) 页面。
createdAt 和 updatedAt?生成的代码没有 schema 选项。加上第二个参数 new Schema({...}, { timestamps: true }),Mongoose 就会维护这两个字段;同时删掉来自 JSON 的同名字段。
required 字段里存空字符串会怎样?Mongoose 对字符串的 required 校验器会把 "" 视为缺失。正因为如此,示例中为空字符串的字段一开始就不会生成 required。