如何在Mongoose嵌套数组中按指定条件查询对应userId
问题排查点
- 参数拼写错误:函数定义的形参为
publiserId(缺失字母h),查询条件中引用的是publisherId,二者不匹配导致查询时publisherId实际为undefined,无法匹配到对应数据。 - 数组查询语法错误:查询条件中
"books.$.bookId"写法错误,$占位符仅用于更新操作、结果投影场景下定位匹配的数组下标,查询数组内子字段匹配值时,直接写"books.bookId"即可。 - 冗余Promise包装:Mongoose的
findOne方法本身返回Promise实例,手动封装一层属于不必要操作,还可能增加异常捕获的逻辑漏洞。
修正后代码
const allTheRelatedData = (publisherId, bookId) => { return myBookSchema .findOne( // 查询条件 { publisherId: publisherId, "books.bookId": bookId }, // 投影配置:仅返回userId和匹配到的books元素,不需要返回全量books数组 { userId: 1, "books.$": 1 } ) .then(data => { console.log(data); // 如果需要直接返回userId,可直接 return data?.userId return data; }) .catch(error => { console.log(error); throw error; }); };
如果需要获取匹配的book条目内的userId,直接取返回结果中books[0].userId即可;如果是文档顶层的userId,直接取data.userId即可。
内容的提问来源于stack exchange,提问作者Agent K
相关产品推荐
相关产品推荐

