2

Consider the following Mongoose schema:

new mongoose.Schema({
    attributes: [{
        key: { type: String, required: true },
        references: [{
            value: { type: String, required: true },
            reference: { type: mongoose.Schema.Types.ObjectId, required: true }
        }]
    }
});

A document that follows this schema would look like this:

{
    attributes: [
        {
            key: 'age', references: [{ value: '35', reference: 298387adef... }]
        },
        {
            key: 'name', references: [{
                value: 'Joe', reference: 13564afde...,
                value: 'Joey', reference: 545675cdab...,
        }
        ...
    ]           
}

I'd like to select attributes according to the following conditions: - the key is name for example - the attribute with key name has a least one reference with a value Joe.

Ideally, I'd like to AND-chain many of these conditions. For example, {'name': 'Joe'} and {'age': '35'}.

I can't seem to find a way of doing that Mongoose. I've tried the following Mongoose queries without any good results (it gives either false positives or false negatives):

 // First query
 query.where('attributes.key', attribute.key);
 query.where('attributes.references.value', attribute.value);

 // Second
 query.and([{ 'attributes.key': attribute.key }, { 'attributes.$.references.value': attribute.value }]);

 // Third
 query.where('attributes', { 'key': attribute.key, 'references.value': { $in: [attribute.value] }});

So how do I do it?

4

1 回答 1

2

您可以使用它elemMatch来查找包含attributes匹配多个术语的元素的文档:

query.elemMatch(attributes, { key: 'name', 'references.value': 'Joe' })

但是,您不能将多个elemMatch调用链接在一起,因此如果您想要将多个调用与这些调用相结合,则需要使用$andand$elemMatch而不是链接Query方法调用来显式构建一个查询对象。

于 2013-05-28T12:50:47.607 回答