如何在Node.js/MongoDB中修改Schema向对象添加多数组
解决方案
1. 修改Mongoose Schema
直接在navigation对象中添加键为2、3、4的字段,类型和1保持一致,都是[subSchema]数组:
const PostSchema = mongoose.Schema({ navigation: { 1: [subSchema], 2: [subSchema], 3: [subSchema], 4: [subSchema] } })
如果希望这些字段为可选(允许部分字段为空),可以添加default: []设置默认空数组,避免字段缺失:
const PostSchema = mongoose.Schema({ navigation: { 1: { type: [subSchema], default: [] }, 2: { type: [subSchema], default: [] }, 3: { type: [subSchema], default: [] }, 4: { type: [subSchema], default: [] } } })
2. 调整Post API代码
你当前的API代码无需大幅修改,只要前端请求的req.body.navigation中包含2、3、4字段的数据,Mongoose就会自动根据新Schema存储这些内容。如果需要确保即使前端未传某些字段,数据库中仍保留对应空数组,使用上述带default的Schema即可。
示例存储的数据结构如下:
{ "navigation": { "1": [test], "2": [test2], "3": [test3], "4": [test4] } }
内容的提问来源于stack exchange,提问作者Rafa Soto Chan
相关产品推荐
相关产品推荐

