Mongoose外部Schema能否移除_id?无ID方案可行吗?
Mongoose外部Schema移除_id的实现方案
核心结论
外部Schema(非嵌套的独立Schema)完全可以移除默认的_id字段,你给出的代码就是正确的实现方式——在Schema定义的第二个配置参数中添加{ _id: false },这样Mongoose就不会自动生成并向数据库存储_id字段。
完整代码示例(结合Express)
const mongoose = require('mongoose'); const express = require('express'); const app = express(); // 解析JSON请求体 app.use(express.json()); // 定义不带_id的外部Schema const planSchema = new mongoose.Schema({ name: String, description: String }, { _id: false }); // 创建对应的模型 const Plan = mongoose.model('Plan', planSchema); // 示例:新增计划的接口 app.post('/plans', async (req, res) => { try { const newPlan = new Plan(req.body); const savedPlan = await newPlan.save(); // 返回的文档中不会包含_id字段 res.status(201).json(savedPlan); } catch (error) { res.status(400).json({ message: error.message }); } }); // 连接MongoDB数据库 mongoose.connect('mongodb://localhost:27017/your_database_name') .then(() => console.log('数据库连接成功')) .catch(err => console.error('数据库连接失败:', err)); // 启动Express服务 app.listen(3000, () => console.log('服务运行在 http://localhost:3000'));
注意事项
- 该配置仅作用于当前Schema,不会影响项目中其他Schema的
_id生成逻辑。 - 如果业务需要唯一标识文档,可以自行定义字段(如
planId)并设置唯一索引,替代默认_id的作用:const planSchema = new mongoose.Schema({ planId: { type: String, unique: true, required: true }, name: String, description: String }, { _id: false });
内容的提问来源于stack exchange,提问作者Ayman_Alkhatib
相关产品推荐
相关产品推荐

