【发布时间】:2019-05-17 09:15:24
【问题描述】:
我正在尝试查询收藏某个活动的所有用户。事件 ID 存储在嵌套对象的用户文档中。
我的架构是这样的
{
email: {
type: String,
unique: true,
required: [true, 'Email is required!'],
trim: true,
validate: {
validator(email) {
const emailRegex = /^[-a-z0-9%S_+]+(\.[-a-z0-9%S_+]+)*@(?:[a-z0-9-]{1,63}\.){1,125}[a-z]{2,63}$/i;
return emailRegex.test(email);
},
message: '{VALUE} is not a valid email!',
},
},
role: {
type: String,
enum: ['admin', 'user', 'planner'],
default: 'user',
},
name: {
type: String,
trim: true,
},
username: {
type: String,
trim: true,
unique: true,
},
password: {
type: String,
required: [true, 'Password is required!'],
trim: true,
minlength: [6, 'Password needs to be longer!'],
validate: {
validator(password) {
return password.length >= 6 && password.match(/\d+/g);
},
},
},
picture: {type: String},
favorites: {
events: [
{
type: Schema.Types.ObjectId,
ref: 'Event',
},
],
},
}
我将如何编写这个查询?
我已经尝试了$elemMatch 和普通查询的各种组合
【问题讨论】:
-
db.collection.find({ "favorites.events": userId }) -
感谢@AnthonyWinzlet 出人意料地奏效了,问题是我之前尝试过时传递的是字符串而不是传递对象ID!
标签: arrays node.js mongodb express mongoose