I would like to use $and in my MEANJS application. I use $resource in my service to get all the query parameters and would like to perform and AND operation. My service looks like this:
//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
};
}
})();
In my Ctrl i use functions to set @count and the other parameters to build the query i need. What i would like to accomplish is to have multiple values for @count and the others. I this possible in the frontend or do i need to do it in the backend (if so, can you point me in the right direction on where to start there?)
You just need the operator in
of mongoose
for your case.
Let's say, you wanna get the results where syllableCount = 1
or 2
and syllableStructur = einfach
or komplex
:
// Inside your controller function
YourModel.
find({}).
where('syllableCount').in([1, 2]).
where('syllableStructur').in(['einfach', 'komplex']).
exec(callback);
From your frontend, you would pass these variables as arrays of possible values. Then just change the [1, 2]
and ['einfach', 'komplex']
from my example for your req.body.syllableCount
or whatever you name it.
If you are using MEAN stack(you need to applied Mongoose & Express), I will recommend a very powerful library -- express-restify-mongoose . Please follow the link to use it. After applied this library into your project, it will automatically generate RESTful URL webservice for you to CRUD data in mongoDB by HTTP requests.
After you applied express-restify-mongoose, you can use another library -- request and follow this example to query mongoDB with $and criteria:
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);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.