Mongoose操作MongoDB向多层嵌套数组插入元素的实现方法
Mongoose三层嵌套数组插入数据问题解决方案
问题背景
已定义的Notes集合Schema如下:
const notesSchema = mongoose.Schema({ college: {type:String}, year: {type:String}, sem: {type:String}, branch:{type:String}, subjects: [ { subject_id:{type:String}, name:{type:String}, codename: {type:String}, notes: [ { notes_id:{type:String}, title: {type:String}, material: [ { material_id:{type:String}, heading:{type:String}, link: {type:String} } ] } ] } ] })
需求为向material数组插入新对象,该数组嵌套在notes数组内,notes数组又嵌套在subjects数组中。
此前尝试的写法执行失败,错误尝试代码如下:
try { notes.updateOne({ $and:[ {_id: '62a61949dc0f920ae99fc687'}, {'subjects.notes.notes_id':'221fad-f35c-ee2a-65b3-8531dbfcf732'}] }, {$push:{'subjects.0.notes.$.material': [{ material_id: "hfklahfhoabfoab", heading: "Prime", link: "wwo.prime.com" }] }}
完整路由功能代码如下:
router.get('/populate',async (req,res)=>{ // const {data} = req.body // const link = "www.wiki.com" try { notes.updateOne({ _id: '62a61949dc0f920ae99fc687', 'subjects.notes.notes_id': '221fad-f35c-ee2a-65b3-8531dbfcf732', }, {$push:{'subjects.0.notes.$.material': [{ material_id: "hfklahfhoabfoab", heading: "Prime", link: "wwo.prime.com" }] }} ) console.log("posted") const alreadyexist = await notes.find({$and:[{"year":'3'},{"sem":'2'}]}) res.send(alreadyexist) // console.log(updata) } catch (error) { console.log(error) } } )
当前数据库状态参考:
错误原因
原有写法存在三个核心问题:
updateOne是异步方法,未加await就执行后续逻辑,更新操作不会正常提交- 硬编码
subjects.0固定匹配第一个subject元素,目标notes不在第一个subject下时必然匹配失败 - 单个
$占位符仅支持定位第一层查询匹配的数组元素,无法直接定位第二层嵌套的notes数组;且$push直接传入数组时,会将整个数组作为单个元素插入,而非插入数组内的对象。
正确实现代码
使用arrayFilters配置匹配多层嵌套数组的条件,给异步方法加await,$push插入单个对象时直接传对象即可,多对象插入可搭配$each使用:
router.get('/populate',async (req,res)=>{ try { // 加await等待更新执行完成 await notes.updateOne( // 第一层匹配条件:文档ID { _id: '62a61949dc0f920ae99fc687' }, { $push: { // 用过滤定位符$[subject]、$[note]指向对应数组元素 'subjects.$[subject].notes.$[note].material': { material_id: "hfklahfhoabfoab", heading: "Prime", link: "wwo.prime.com" } } }, { // 配置数组过滤条件,定位符合要求的subject和note元素 arrayFilters: [ // 不需要匹配subject属性时可留空匹配所有subject,也可自行添加subject的匹配规则 {}, { 'note.notes_id': '221fad-f35c-ee2a-65b3-8531dbfcf732' } ] } ) console.log("posted") // 逗号分隔的查询条件默认就是与逻辑,不需要额外包$and const alreadyexist = await notes.find({year:'3', sem:'2'}) res.send(alreadyexist) } catch (error) { console.log(error) } } )
如果需要同时匹配指定subject,只要给arrayFilters的第一个过滤项加条件即可,比如{ 'subject.subject_id': '目标subjectID' },不需要硬编码数组下标。
注意:该写法需要MongoDB 3.6及以上版本支持,目前主流Mongoose配套的MongoDB版本均满足要求。
内容的提问来源于stack exchange,提问作者unknown Gabbar
相关产品推荐
相关产品推荐

