Wanted to use like query in lbservices for angular - angularjs

I want to query all the names starting with p (case insensitive).
Below is the query object and Organisation is my generated lb-service name
query = {
filter: {
order: 'updatedAt ASC',
where: {name: {ilike: 'P%'}}
};
Organisation.find({filter: query.filter})

You can use regex for this.
Organisation.find({name: {$regex: new RegExp('^P$', "i")}}).sort('updatedAt').all(function(res) {
//Do your action here..
});

Related

How to create req.query.parameter?

I don't how to do it, please help the kidding develop (T_T).
It shows "undefined" when I'm executing:
router.get("/filter-report/", verifyToken, (req, res) => {
queries.report_table
.Filter_leave()
.then(requests => {
let leavetype = req.query.request_category;
let depart = req.query.department;
let fname = req.query.first_name;
let obj = {filter: leavetype + ''+ depart+''+fname}
console.log(obj);
res.json(obj);
});
});
The URL should look like /filter-report?request_category=category&department=dev&first_name=test
but I think the error is in line 2, queries is not defined/initialized
Adding to Vinil's answer. Queries can be accessed from req. It is an Object. So if your url looks like this:
/filter-report?request_category=category&department=dev&first_name=test
Then your query object will be looking like this:
{
request_category: category,
department: dev,
first_name: test
}
And you can access that query as usual using req.query.request_category, etc.

Mongoose stops to $push to array if the field already exists in a document

I am using Node and Mongoose, and trying to set an array of ISODate elements:
"visitLog" : [
ISODate("2017-10-22T22:43:49.571Z"),
ISODate("2017-10-22T22:44:39.572Z"),
ISODate("2017-10-22T23:35:36.111Z"),
ISODate("2017-10-22T23:48:26.516Z"),
ISODate("2017-10-22T23:50:33.378Z"),
ISODate("2017-10-22T23:53:56.227Z"),
ISODate("2017-10-22T23:57:20.986Z")
]
So I had an existing schema where visitLog field did not existed, added new field to a schema - visitLog: [ {type: Date, default: '' }],and it worked - the result is what you see above.
But when I created a new document with updated schema that already has an empty array in it - "visitLog" : [ ] , $push just stopped working.
Here is mongoose query, if needed:
// conditions is a ternary operator that checks whether req.body username
// is an email or not, and puts needed condition to a query
var conditions = (!/^[a-zA-Z0-9\-\_\.\+]+#[a-zA-Z0-9\-\_\.]+\.[a-zA-Z0-9\-\_]+$/.test(req.body.username)) ? ' {email: req.body.username } ' : ' {username: req.body.username } ';
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { upsert: true };
User.findOneAndUpdate(conditions, fieldsToSet, options, function(err, user) { ...
The working document was created in mongo console, while the second was generated on a server, but I can't how can this make any difference.
Using $push shuld work with empty arrays. Can someone explain what's wrong here?
Thank you.
Edit
It figures that using findByIdAndUpdate without conditions works for both documents:
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { new: true };
req.app.db.models.User
.findByIdAndUpdate(req.user.id, fieldsToSet, options, function(err, user) {
You can do with the following query.
User.findOne(condiitons, (err, user) => {
if (user) {
var date = new Date().toISOString();
user.visitLog.push(date);
user.save();
...
}
});

filter through scope array ignoring certain items

I have a scope array called $scope.groups
$scope.groups = [{
id: 1,
name: "Group 1"
},
{
id: 2,
name: "Group 2"
}]
When I updated one of the groups I need to check if that updated group exists in the groups array however when i filter the array it checks the group i need to update as well so it outputs "Group exists".
function ifGroupExists(GroupName,GroupId) {
var match;
match = $scope.groups.filter(function (item) { return angular.lowercase(item.name) === angular.lowercase(GroupName); });
if (match.length > 0) {
console.log("group exists");
return true;
}
else {
console.log("group does not exists");
return false;
}
}
This code works if im adding a totally new group to the array however how do i edit this so that it doesnt check the group currently being updated and have it so it only checks the other groups to see if there is a match.
Can someone help? Im sure there is a simple way to do this. Just cant seem to figure it out..
It can be simple like, just pass the currently updating group to function as well, and ignore it in the filter.
Code should be like :
function ifGroupExists(groupName_filter, groupName_current) {
var match;
match = $scope.groups.filter(function (item) {
return (angular.lowercase(item.name) === angular.lowercase(groupName_filter) &&
angular.lowercase(item.name) !== angular.lowercase(groupName_current));
});
return (match.length > 0);
}
and I hope you need console.log only during development :), so return can be simplified.
Further: If you have groupName_current as $scope property, then use it directly, no need to pass.

Output all documents in mongoose

I am using mongoose ODM and have a schema which looks like this:
var banSchema = new Schema({
userid: { type: String, required: true, unique: true },
name: String,
groupid: String,
reason: String,
timestamp: Date
});
I want to output every single user id from all documents in the collection. I am using this query to obtain the userid objects. However I cannot seem to get the full list automatically. I have to manually enter the object number as seeen below:
bot.onText(/\/sync/i, function (msg) {
var fromId = msg.from.id;
var chatId = msg.chat.id;
if (fromId == config.sudo) {
console.log('Sudo Confirmed And Authorized!');
Ban.find({}, function (err, obj) {
console.log(obj[0].userid); // Returns A Single ID
console.log(obj[1].toObject().userid); // Returns a different ID
bot.sendMessage(chatId, obj[1].toObject().useridid);
});
} else {
console.log('Someone Is Trying To Act Like Sudo! *sigh*');
bot.sendMessage(chatId, 'You Are Not A Mod!');
}
});
This however does not return a full list of id's as I want. How could I solve this issue?
The code above is for a telegram bot which on a /sync command it should return a message with all ids from the collection.
Telegram bot API Limits
Due to the API limits, the entire output should be in a single message.
var query = Ban.find({}).select({
"userid": 1,
//Add more column fields here
"_id": 0 //Ensures _id is not displayed
});
var arr = [];
query.exec(function (err, results) {
if (err) throw err;
results.forEach(function (result) {
arr.push(result.userid);
// Add more column fields here;
});
var fixedJoin =arr.join("\n");
console.log(fixed);
bot.sendMessage(chatId, 'List\n\n' + fixedJoin);
});
The easiest way to get all values of a particular field across all docs in the collection is to use distinct:
Ban.distinct('userid', function (err, userids) {
// userids is an array containing all userid values in the collection.
// string.join into a single string for the message.
bot.sendMessage(chatId, 'USER IDs\n\n' + userids.join('\n'));
});
Use this syntax
Ban.find({}).
select('userid').
exec(function(err, result) {
//result is array of userid of all document
});
You can use this syntax:
Ban.find({}, 'userid', function(err, users) {
users.forEach(function(user) {
console.log(user);
bot.sendMessage(chatId, 'users \n' + user);
});
})

CakePHP: Rename field name without change the hierarchy

I have this function write in a CakePHP model:
public function getPeopleByName($name){
$this->unbindModel(array('hasMany' => array('OfficePersonTask')));
$options['fields'] = array("Person.id", "CONCAT(Person.first_name, ' ', Person.last_name) AS full_name");
return $this->find('all', $options);
}
This gave me the following json:
{
People:[
{
0:{
full_name:"Groucho Marx"
},
Person:{
id:"1"
}
},
{
0:{
full_name:"Giovanni Ferretti"
},
Person:{
id:"2"
}
}
]
}
I would that *full_name* will be part of Person group (actually is in a group called 0, all alone). How I can do that?
Use a virtual field in the model rather than a MySQL function in your find. There are some ways to query for data as you are trying to, but you have to account for data being returned in an indexed array rather than the normal associative.

Resources