You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于给定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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:24:06