如何基于给定MongoDB样本对象创建可正常运行的Mongoose Schema
Mongoose Schema 调整方案
存在的问题
- 字段类型定义不符合Mongoose规范:字符串、数字类型需要使用全局构造函数
String、Number,不能使用小写字符串值"string"、"number" - 如果需要严格匹配你提供的MongoDB样本文档结构,额外添加的
date字段可以选择删除,若业务需要保留也可以继续使用,因为配置了默认值不会影响正常写入 - 模型命名规范:Mongoose默认会将
model()方法第一个参数转为小写复数作为对应的集合名,如果你需要指定固定集合名,可以传入第三个参数明确指定
修正后代码
const mongoose = require('mongoose'); const locationSchema = new mongoose.Schema({ location: { type: String, required: true }, numbers:{ type: Number, required: true }, available:{ type: [Boolean], required: true }, // 不需要date字段直接删掉下面这部分即可 date:{ type: Date, default: Date.now, } }) // 第三个参数可选,用于指定MongoDB中对应的集合名,示例对应集合名为locations const locations = mongoose.model('Location', locationSchema, 'locations'); module.exports = locations;
内容的提问来源于stack exchange,提问作者Ubron
相关产品推荐
相关产品推荐

