javascript - Mongoose:使用填充数据构建查询
问题描述
我有一个包含组和用户的集合:
组架构:
const groupSchema = new mongoose.Schema({
name: String,
members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
});
用户架构:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
min: 5,
max: 255
},
password: {
type: String,
require: true,
min: 6,
max: 1024,
},
});
现在,我想构建一个查询来查找用户所属的所有组。我试图像这样构建它:
const userId = '...';
const groups = await Group.find({members: userId}).populate('members');
通过这个查询,我得到一个空数组,这不应该是结果。如何修复我的查询?
没有任何过滤器的查询结果如下所示:
[
{
"members": [
{
"_id": "6044c5d9b63a2a0ce0d0a32e",
"name": "Test",
"email": "test@test.com"
}
],
"_id": "6045e9837e66e80eca2a689c",
"name": "Test",
"__v": 0
}
]
解决方案
检查数据库中的数据后发现错误。问题是,members
数组中的 id 存储为String
. 将类型更改ObjectId
为查询后工作正常。
推荐阅读
- android - room rxjava 多次调用 onNext,即使没有更改数据库
- java - 即使存在数据,ResultSet 也总是返回 null?
- html - “时钟”字体真棒图标未显示在我的网页上
- clojure - 为什么 clojure fn 的结果包含括号?
- amazon-web-services - 有没有办法为 S3 lambda 过滤器包含 aws cognito 身份 ID?
- html - Wordpress - 移动设备上的第一列低于另一列
- react-native - 清除浏览器 cookie React Native 0.60
- javascript - PDFJS:无效的 PDF 结构
- flutter - 颤振 | Dio Package ...在后台下载大文件
- spring - Spring boot 项目 .war 文件在 web-apps 文件夹中部署后不会自动启动