【问题标题】:express-restify-mongoose query multiple attributesexpress-restify-mongoose 查询多个属性
【发布时间】:2017-06-04 20:54:25
【问题描述】:

问题:

我正在尝试使用 express-restify-mongoose 从 angular2 向我的 nodejs 服务器发送一个查询,该查询将搜索超过 1 个属性。

我所拥有的(工作):

let regex = '{"title":{"$regex":"(' + text + ')"}}';

我尝试过/想要的(不起作用):

let regex = '{"title":{"$regex":"(' + text + ')"}, "content":{"$regex":"(' + text + ')"}}';

documentation 中没有 2+ 属性的示例。

问题:

这甚至可以通过单个查询来实现吗?如果不是,我怎么能最好地解决这个问题?

编辑: 如果没有该库,也会对解决方案感到满意,但最好还是涉及单个查询。

2。编辑: 这是我调用来获取数据的完整函数(不是工作示例):

getPostsQuery(text: string){
    let query = '';
    let limit = 25;
    let headers = new Headers();
    let authHeaders = this.authService.getAuthHeader();
    headers.append(authHeaders.name, authHeaders.value);
    let regex = '{"title":{"$regex":"(' + text + ')"}, "content":{"$regex":"(' + text + ')"}}';

    let populate = [
        {path: "tags"},
        {path: "creator"}
    ];

    query += `&limit=${limit}&query=${regex}`;

    return this.http.get(`${this.apiUrl}/post?populate=${JSON.stringify(populate)}${query}`, {headers})
        .map((response: Response) => response.json());
}

【问题讨论】:

  • 第二个查询会发生什么?没有数据?错误?
  • 错误,无效查询:/

标签: node.js mongodb angular express mongoose


【解决方案1】:

您可以使用 MongoDB 的标准查询条件/条件语法。

根据您的要求使用$and$or 运算符:

{ $and: [{"title": {"$regex": "(' + text + ')"}}, {"content": {"$regex": "(' + text + ')"}}] }

{ $or: [{"title": {"$regex": "(' + text + ')"}}, {"content": {"$regex": "(' + text + ')"}}] }

【讨论】:

  • 您传递的正则表达式字符串是什么?
  • 我可以把这个放在网址里吗?见我的 2. 编辑澄清
  • 对不起,我不明白你的意思 把这个放在 url 中
  • 我认为您的查询中缺少 &在填充和查询参数之间)。应该是return this.http.get(`${this.apiUrl}/post?populate=${JSON.stringify(populate)}&${query}`, {headers}) .map((response: Response) => response.json());
  • 我想通了,通过使用JSON 然后JSON.stringify(object) 它起作用了。
【解决方案2】:

【讨论】:

  • 它如何回答/解决 OP 提出的问题?
猜你喜欢
  • 1970-01-01
  • 2021-10-23
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 1970-01-01
  • 2014-01-09
  • 2020-12-14
相关资源
最近更新 更多