[英]Mongodb query to find element value type of nested array or object in a field
[英]MongoDb Query on array field of a nested object
我正在嘗試查詢喜歡該事件的所有用戶。 事件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
和普通查詢的各種組合
$elemMatch
應該用作對象,但在數組favorites.events
每個元素都是String(ObjectID),因此,應使用$eq
將每個元素與String匹配,String是所需事件的ID。
解決方案是:
User.find({
'favorites.events': {
'$elemMatch': {
'$eq': id
}
}
})
$elemMatch
文檔在這里https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#element-match
和$eq
文檔在這里https://docs.mongodb.com/manual/reference/operator/query/eq/
您應該對Mongo的簡單結構提出疑問。 例如,這是我為您測試的問題
const Schema = mongoose.Schema;
const EventSchema = new Schema({
title: String
})
const UserSchema = new Schema({
username: String,
favorites: {
events: [{
type: Schema.Types.ObjectId,
ref: 'Event',
}]
}
});
const User = mongoose.model('User', UserSchema);
const Event = mongoose.model('Event', EventSchema)
app.get('/users/event/:id', (req, res) => {
const {id} = req.params;
console.log(id);
User.find({
'favorites.events': {
'$elemMatch': {
'$eq': id
}
}
}).then(u => res.send(u)) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.