我试图在客户端的Meteor集合中查询数组中的特定元素,但Minimongo不支持$运算符。有没有其他方法可以过滤我的查询,使其只返回数组中的特定元素?
我的收藏结构是这样的:
{
"userID": "abc123",
"array": [
{
"id": "foo",
"propA": "x",
"propB": "y"
},
{
"id": "bar",
"propA": "a",
"propB": "b"
}
]
}我正在尝试编写一个只返回数组中id为"foo“的对象的查询。在Mongo中,查询应该是这样:
collection.find({
"userID": "abc123",
"array.id": "foo"
}, {
"array.$": 1
});然而,Minimongo在投影中不支持$运算符,所以这会抛出一个错误。我尝试过使用$elemMatch进行类似的结构化查询,并尝试了solution described here,但它没有完成我想要做的事情。
是否有其他方法可以使用Minimongo查询此数组中的一个元素?
发布于 2016-03-24 07:27:11
您可以使用findWhere来提取数组中的第一个匹配对象。试一试这样的东西:
// Find all documents matching the selector.
const docs = Collection.find({ userId: 'x', 'array.id': 'y' }).fetch();
// For each document, find the matching array element.
for (let doc of docs) {
let obj = _.findWhere(doc.array, { id: 'y' });
console.log(obj);
}https://stackoverflow.com/questions/36190401
复制相似问题