Mongoose query find() returns nothing - angularjs

I'm querying db with 2 conditions, keyword and user id, both returns correctly in console log but returns nothing, not null, or [], just blank. Something is wrong with the syntax?
app.get("/api/client?", function (req, res) {
console.log("Search > " + JSON.stringify(req.query));
//Search > {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}
var keyword = req.query.keyword;
var user_id = req.query.id;
Client.find({
$and: [{
"firstname": new RegExp('^' + keyword + '$', "i")
},
{
userid: user_id
}
]
}, (err, result) => {
if (err) {
console.log(err);
}
res.status(200).json(result);
console.log("Result is... " + result)
//Result is
});
});
Alternatively, I tried without query, just search all based on user id and it works, it returns all records in db
app.get("/client", function (req, res) {
var user_id = req.query.id;
Client.find({
userid: user_id
}, (err, result) => {
if (err) {
console.log(err);
}
res.status(200).json(result);
});
});

Found the solution! Noob mistake, I was caught up with what was working in search all, var user_id = req.query.id but in fact when I passed in "filterby", based on
console.log {"keyword":"emily","filterby":"5a25f3d1d4b3e30792dd53ca"}
so it should be
var keyword = req.query.keyword;
var **filterby** = req.query.id;
Client.find({
$and: [{
"firstname": new RegExp('^' + keyword + '$', "i")
},
{
userid: **filterby**
}
]
}

Related

Cashfree Payment gateway Integration in react native and laravel (orderAmount is required error)

I am integrating CashFree payment gateway in react native app (Android). I am following this documentation https://docs.cashfree.com/docs/react-native-2-0-sdk#web-checkout. While implementing I am getting response as
{"type":"CashFreeResponse","txMsg":"orderAmount not provided","txStatus":"FAILED"}
But I am passing all the params what all required to proceed for payment.
const handlePayment = response => {
console.log('amount', total);
var mode = 'TEST';
var map = {
"appId": response.credentials.app_id,
"orderId": response.credentials.order_id,
"orderCurrency": 'INR',
"orderAmount": 150, //parseInt(response.data.price)
"customerPhone": response.user.mobile,
"customerEmail": response.user.email,
"tokenData": response.payment_info.cftoken,
"orderNote": 'Subscription Payment',
"notifyUrl": '',
"customerName": response.user.name,
};
console.log('data', map);
RNPgReactNativeSDK.startPaymentWEB(map, mode, result => {
console.log(result);
var obj = JSON.parse(result, function (key, value) {
console.log(key + '::' + value);
// Do something with the result
});
});
};
As per the Documentation mentioned on their website you need to enter the order amount as a string.
const handlePayment = response => {
console.log('amount', total);
var mode = 'TEST';
var map = {
"appId": response.credentials.app_id,
"orderId": response.credentials.order_id,
"orderCurrency": 'INR',
"orderAmount": '150',
"customerPhone": response.user.mobile,
"customerEmail": response.user.email,
"tokenData": response.payment_info.cftoken,
"orderNote": 'Subscription Payment',
"notifyUrl": '',
"customerName": response.user.name,
};
console.log('data', map);
RNPgReactNativeSDK.startPaymentWEB(map, mode, result => {
console.log(result);
var obj = JSON.parse(result, function (key, value) {
console.log(key + '::' + value);
// Do something with the result
});
});
};

mongodb sending userid's in an array as a query and return the json object of the users present in collection

I have a collection of online users here goes its model
var SessionDetailSchema = mongoose.Schema({
providerID: {
type: String
},
firstName: {
type: String
},
email: {
type: String
},
status: {
type: String
}
},{ timestamps: true });
var sessionDetail = module.exports = mongoose.model('OnlineUser', SessionDetailSchema);
I am trying to send an array of providerID's so that I wanted to check the collection which all providerId's are present and return me those providerID details.
and this is what I tried
router.post('/sessiondetails:find', function (req, res, next) {
console.log(req.body.providerID)
sessionDetail.find({ "providerID": { $in: req.body.providerID} }, function (err, users) {
if (users) {
console.log(users)
} else {
console.log("not there")
}
})
})
unfortunately, I am getting the only first providerid response for multiple times.
i am sending the array from the postman it looks like this
{
"providerID":["1090867867720278", "104761648907225164100", "114316680403119099502", "103668441331122956874"]
}
can some help me? thanks in advance.

save array of objects to the mongo database using node, express

I am trying to pre-load array of objects to MongoDB as below:
the below code works if I do one object at a time. that is,
if I set:
tmp_obj = {
id:1,
name: 'Tmp 1'
}
model file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TmpSchema = new Schema({
id: Number,
name: String
});
var Tmp= mongoose.model('Tmp', TmpSchema);
module.exports = Tmp;
routes file
var express = require('express');
var router = express.Router();
var Tmp = require('../models/tmp');
var tmp_obj = [
{
id:1,
name: 'Tmp 1'
},
{
id:2,
name: 'Tmp 2'
},
{
id:3,
name: 'Tmp 3'
}
];
var tmp = new Tmp(tmp_obj);
tmp.save(function (err) {
if (err) return console.log(err);
console.log('tmp saved to the database');
return res.redirect('/login');
})
how do I push an array of objects to the mongo? and also I have multiple collections to add. so, do I do something like:
tmp1.save(function (err) {
if (err) return console.log(err);
console.log('tmp1 saved to the database');
tmp2.save(function (err) {
if (err) return console.log(err);
console.log('tmp2 saved to the database');
return res.redirect('/login');
})
})
Another alternative is to use .create() method, it could accept an array of objects or a single object, and you don't need to create a model instance (i.e var tmp = new Tmp(tmp_obj);), here is an example:
var Tmp = require('../models/tmp');
var tmp_obj = [
{ id:1, name: 'Tmp 1' },
{ id:2, name: 'Tmp 2' },
{ id:3, name: 'Tmp 3' }
];
Tmp.create(tmp_obj, function (err, temps) {
if (err) {
console.log(err);
// terminate request/response cycle
return res.send('Error saving');
}
res.redirect('/login');
});
One last thing, don't forget to terminate the request/response cycle if an error has been occurred, otherwise the page will hangs
You can use the method insertMany from mongoose to insert multiple document at once.
From the documentation of mongoose v5.0.4
var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
Movies.insertMany(arr, function(error, docs) {});
An alternative using .save() would be
// Create all objects
const objects = tmp_obj.map(x => new Tmp(x));
try {
// Saves objects
const docs = await Promise.all(objects.map(x => x.save()));
} catch(e) {
// An error happened
}
But you should not use it since insertMany is way better

In NodeJS, convert database query output to Json format

This is my code:
oracledb.getConnection(
{
user : "user",
password : "password",
connectString : "gtmachine:1521/sde1"
},
function(err, connection)
{
if (err) { console.error(err); return; }
connection.execute(
"SELECT filetype, filetypeid from filetype where filetypeid < 6",
function(err, result)
{
if (err) { console.error(err); return; }
response = result.rows;
console.log(response);
res.end(JSON.stringify(response));
});
This is the output
[["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]]
But my front end angularjs is expecting something in this format:
[{"filetype":"Ascii Text","filetypeid":1},{"filetype":"Binary","filetypeid":2}]
Does any one know what is the standard way to convert this?
These will convert your array of arrays into an array of objects:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(
function(item) {
return {
filetype: item[0],
filetypeid: item[1]
}
}
);
console.log(results);
And in ES6:
var results = [["Ascii Text",1],["Binary",2],["Graphics - GIF",3],["Graphics - JPEG",4],["HTML",5]];
results = results.map(item => ({filetype: item[0], filetypeid: item[1]}));
console.log(results);

Angular Resource update method with an array as a parameter

I have been googleing this for a few weeks with no real resolution.
I am sure someone will mark this a duplicate, but I am not sure it really is, maybe I am just being too specific, anyway here goes.
I am using angular in a node-webkit app that I am building. I have an api built in express and I am using MongoDB (#mongolab) with Mongoose for the DB.
I had this working fine as long as all of the data types were simple strings and numbers. but I had to restructure the data to use arrays and complex objects. After restructuring the data I was able to get post API calls to work fine, but I cannot get my PUT calls to work at all.
The data looks like this:
itemRoles was an array, but I thought it was throwing the error I am getting now, so I converted it back to a string.
itemStats is causing the problem. Angular is looking for an object, but itemStats is an array (I think anyway). itemStats used to be a string as well, but its easier to work with in my view if it is an array of objects with key:value pairs, which is why I altered it.
I should note I am new to MongoDB as well, first time using it.
{
"_id": {
"$oid": "55a10b9c7bb9ac5832d88bd8"
},
"itemRoles": "healer,dps",
"itemRating": 192,
"itemName": "Advanced Resolve Armoring 37",
"itemClass": "consular",
"itemLevel": 69,
"itemStats": [
{
"name": "Endurance",
"value": 104,
"_id": {
"$oid": "55a10b9c7bb9ac5832d88bda"
}
},
{
"name": "Willpower",
"value": 124,
"_id": {
"$oid": "55a10b9c7bb9ac5832d88bd9"
}
}
],
"__v": 0
}
The Mongoose Schema looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var stats = new Schema({
//name: String,
//value: Number
//});
var armoringSchema = new Schema({
itemType: String,
itemClass: String,
itemRoles: String,
itemLevel: Number,
itemName: String,
itemRating: Number,
itemStats: [{ name:String, value:Number}]
});
module.exports = mongoose.model('Armor', armoringSchema);
Express API Route:
/ on routes that end in /armors/:id
// ----------------------------------------------------
router.route('/armors/:id')
// get method omitted
// update the armoring with specified id (accessed at PUT http://localhost:8080/api/armors/:id)
.put(function(req, res) {
// use our armor model to find the armor we want
Armoring.findById({_id: req.params.id}, function(err, armor) {
if (err) {
return res.send(err);
}
for(prop in req.body) {
armor[prop] = req.body[prop];
}
// save the armor
armor.save(function(err) {
if (err) {
return res.send(err);
}
res.json({success:true, message: 'Armor updated!' });
});
});
})
Resource Factory:
swtorGear.factory('armoringFactory', ['$resource', function ($resource) {
return $resource('http://localhost:8080/api/armors/:id', {}, {
update: { method: 'PUT', params: {id: '#_id'}},
delete: { method: 'DELETE', headers: {'Content-type': 'application/json'}, params: {id: '#_id'}}
});
}]);
Route for editing:
.when('/edit/armor/id/:id', {
templateUrl: 'views/modelViews/newArmor.html',
controller: 'editArmorCtrl',
resolve: {
armoring: ['$route', 'armoringFactory', function($route, armoringFactory){
return armoringFactory.get({ id: $route.current.params.id}).$promise;
}]
}
})
Contoller (just the save method, the first part of the controller populates the form with existing data):
$scope.save = function(id) {
$scope.armor.itemStats = [
$scope.armor.stats1,
$scope.armor.stats2
];
$scope.armor.itemRoles = '';
if($scope.armor.role.tank) {
$scope.armor.itemRoles += 'tank';
}
if($scope.armor.role.healer) {
if($scope.armor.itemRoles != '') {
$scope.armor.itemRoles += ',healer';
} else {
$scope.armor.itemRoles += 'healer';
}
}
if($scope.armor.role.dps) {
if($scope.armor.itemRoles != '') {
$scope.armor.itemRoles += ',dps';
} else {
$scope.armor.itemRoles += 'dps';
}
}
console.log($scope.armor);
$scope.armor.$update(id)
.then(function(resp) {
if(resp.success) {
var message = resp.message;
Flash.create('success', message, 'item-success');
$scope.armors = armoringFactory.query();
} else {
var message = resp.message;
Flash.create('success', message, 'item-success');
}
});
}
Formatted data being sent via PUT method (from console.log($scope.armor) ):
Error on save:
I haven't seen nesting schemas in the way that you're doing it. Here's something to try (hard to say if this is it for sure, there's a lot going on):
var armoringSchema = new Schema({
itemType: String,
itemClass: String,
itemRoles: String,
itemLevel: Number,
itemName: String,
itemRating: Number,
itemStats: [{
name: String,
value: Number
}]
});
Also we need to pass in an object to $update instead of just a number. Change $scope.armor.$update(id) to $scope.armor.$update({id: id}).

Resources