如何在 Meteor 的 Mongo 查询中使用变量作为字段名称? [英] How do I use a variable as a field name in a Mongo query in Meteor?

查看:44
本文介绍了如何在 Meteor 的 Mongo 查询中使用变量作为字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在 Meteor 应用程序的 Mongo 查询中使用变量作为字段名称.

How would I go about using a variable as a field name in a Mongo query in a Meteor application.

这是一个例子...

在将集合名称大写为孩子的父 ID 后,这会在我的请求控制器集合上运行查找.子项是 users 字段.

This runs a find on my request controllers collection after capitalizing the collection name for the parent id of a child. The child is the users field.

window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), users: params.child }).count()

如您所见,我的控制器是集合项的变量名称,它允许我使用一行代码来查找控制器/集合的子项,但我需要能够将子字段名称设置为变量.在上面的例子中,它是 users 但我希望它是一个变量名.

As you can see my controller is a variable name for the collection item which allows me to have a single line of code for finding children of controller/collections but I need to be able to set the child field name to a variable. In the above example that would be users but I want it to be a variable name.

我试过了,但没有用.

window[Meteor.request.controller.capitalise()]["find"]({ _id: Session.get('parent_id'), [Session.get('child_collection_name').decapitalise()]: params.child }).count()

哪里

Session.get('child_collection_name').decapitalise()

返回用户

有什么想法吗?如果我能弄清楚如何在meteor 的mongo 查询中使用变量名,它将显着减少我的代码占用空间.

Any ideas? If I can figure out how to use a variable name in a mongo query in meteor it would reduce my code footprint significantly.

推荐答案

查询只是一个 JavaScript 对象,因此您可以逐步构建它:

The query is just a JavaScript object, so you can build it step by step:

var query = { _id: Session.get('parent_id') };
var myCustomField = Session.get('child_collection_name').decapitalise();
var myCustomValue = params.child;
query[myCustomField] = myCustomValue;
var count = SomeCollection.find(query).count();

这样做有用吗?

这篇关于如何在 Meteor 的 Mongo 查询中使用变量作为字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆