MongoDb查询嵌套对象的数组字段

时间:2018-12-17 01:04:45

标签: arrays node.js mongodb express mongoose

我正在尝试查询喜欢该事件的所有用户。事件ID存储在用户文档的嵌套对象中。

我的模式如下

// you can change it in the inspector which is handy
// if i'th value of this array is false
// then i'th CircleDrawer GameObject in objectsToAddCircles array
// won't be affected by this manager
public bool changableCircle[];

void Start() {
    // your code
    changableCircle = new bool[objectsToAddCircles.Length];
}

void Update() {
    for(...) {
        // values which are always overwritten by manager
        if(changableCircle[i]) {
            // values which you don't want to be changed by this manager
        }
    }
}

我将如何编写此查询?

我已经尝试了{ 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', }, ], }, } 和普通查询的各种组合

1 个答案:

答案 0 :(得分:1)

$elemMatch应该用作对象,但是在数组favorites.events中,每个元素都是String(ObjectID),因此,您应该使用$eq将每个元素与ID为您想要的活动。

解决方案是:

User.find({
    'favorites.events': {
        '$elemMatch': {
            '$eq': id
        }
    }
})

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#element-match$elemMatch的文档

此处https://docs.mongodb.com/manual/reference/operator/query/eq/还有$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)) })