2016-08-12 43 views
1

我想在我的MEANJS应用程序中使用$和。我在我的服务中使用$ resource来获取所有查询参数,并且想要执行AND操作。我的服务是这样的:

//Words service used to communicate Words REST endpoints 
(function() { 
    'use strict'; 

    angular 
    .module('words') 
    .factory('querywordsService', querywordsService); 

    querywordsService.$inject = ['$resource']; 

    function querywordsService($resource) { 

    var wordsData = $resource('/api/words/?syllableCount=:count&syllableStructur=:struct&frequency=:freq&emphasis=:emph', 
    { count: '@count', struct: '@struct', freq: '@freq', emph: '@emph' }, 
     { 
     update: { 
      method: 'PUT' 
     } 
     }); 

    return { 
     wordsData: wordsData 
    }; 
    } 
})(); 

在我的Ctrl键我使用的功能设置@count和其他参数来构建查询我所需要的。我想要完成的是为@count和其他人提供多个值。我可能在前端,或者我需要在后端执行它(如果是这样,你能指出我在哪里开始的正确方向?)

+0

要澄清更多,我需要在我的控制器中做这样的事情,有没有办法去做到这一点? 'db.words.find({$ and:[{$ or:[{syllableCount:1},{syllableCount:2}]},{$或:[{syllableStructur:“einfach”},{syllableStructur:“komplex” }]}]})' – d8ta

回答

1

您只需要操作者mongoosein您案件。

比方说,你想得到的结果,其中syllableCount = 12syllableStructur = einfachkomplex

​​

从您的前端,你会通过这些变量可能值的数组。然后,只需更改[1, 2]['einfach', 'komplex']从我的示例req.body.syllableCount或任何其他名称。

+0

这是我的好东西,我不知道这一点,甚至在看过猫鼬的纪录片后。也许我只是想念它。感谢那。我会尽力回来报道! – d8ta

+0

这是行得通的,如果我硬编码它,它会在我的前端显示AND/OR查询结果。所以我现在将它更改为变量,查询应该工作!非常感谢你,我想你救了我的一周^^ – d8ta

-1

如果您使用MEAN堆栈(您需要应用Mongoose & Express),我会推荐一个非常强大的库 - express-restify-mongoose。请点击链接使用它。将这个库应用到您的项目中后,它会自动生成RESTful URL webservice,以便您通过HTTP请求在mongoDB中CRUD数据。

你申请快递-的RESTify,猫鼬后,您可以使用另一个库 - request,并按照这个例子来查询的MongoDB以$标准:

var url = 'http://localhost:7100'; 

// Here is the $and query 
var qs = { 
    query: JSON.stringify({ 
     $and: [ 
      {name: 'Tom'}, 
      {age: {$gt: 20}} 
     ] 
    }) 
}; 


request.get({ 
    baseUrl: url, 
    url: '/api/v1/MyModels', // URL is generated by express-restify-mongoose 
    qs: qs, 
    json: true 
}, function (error, response, body) { 
    if (!error && (response.statusCode == 200)) { 
     console.log(body.length); 
     console.log(body); 
    } else { 
     console.log(error); 
    } 
}); 
+0

是的,我使用MEANJS和yeoman生成器。我只是安装了express-restify-mongoose,但我不确定要把什么放到我的app.js中,因为它已经由生成器设置。任何人都使用这与MEANJS yeoman发电机? – d8ta

+1

我认为这个答案通过添加更多的第三方库增加了不必要的复杂性 –