In NodeJS, convert database query output to Json format - angularjs

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);

Related

Node.js mssql data input layer with connection pool

This question relates to a Node.js mssql API.
I've recently updated my code to use a SQL.ConnectionPool instead of sql.connect which when combined with an async / await function allowed me to get around connection.close() errors.
In my previous (OLD) executeQuery function, I was able to pass an array which I could push values into to use with "request.input(name, value)"
Function call example:
app.get('/api/route/:id', function (req, res) {
var id = req.params.id;
let x = []
if (id != null && id != NaN) {
x.push({
Name: 'id', Value: id
})
var query = `SELECT * from [Table] where ID = #id`
executeQuery(res, query, arr);
} else {
res.send(500)
}
})
OLD Function:
var executeQuery = function (res, query, arr) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log('Error while connecting to the database: ' + err)
res.send(err)
} else {
// Create the request object
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
request.query(query, function (err, rs) {
if (err) {
sql.close();
console.log('Error while querying the database : ' + err);
res.send(err);
} else {
sql.close();
console.log(rs)
res.send(rs)
}
})
}
})
}
NEW Function:
var executeQuery = async function(res, query, arr){
const pool = new sql.ConnectionPool(dbConfig);
pool.on('error', err => {
console.log('sql errors ', err);
});
try {
await pool.connect();
let result = await pool.request().query(query);
console.log('success')
res.send(result);
return {success: result};
} catch (err) {
console.log('error')
console.log(err)
res.send(err);
return {err: err};
} finally {
pool.close();
}
}
Question
How do I go about achieving the same request.input process with a ConnectionPool as I did with my previous function ( like the below )
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
Thank you.

Mongoose query find() returns nothing

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**
}
]
}

update all values in the sub array of one object in mongodb using mongoose

user = {
'userid':'111',
'mail':[{
'time':22222,
'info':'this is a info1',
'read':false,
},{
'time':33333,
'info':'this is a info2',
'read':false,
}]
}
then, I want to change one user's read flag to true, how can i do for it ?
here is my answer:
User.update({
'userid':userid,
'mails':{
'$elemMatch':{
'read':false
}
}
},{
'$set':{
'mail.$.read':false,
'newmail':0,
}
}, { multi: true }, function (err, data) {
if(err > 0){
console.log('ReadMail err', err);
}
});
here is a simple example: my model is User !! my url is the path to the DB
var newUser = new User();
newUser.name = request.body.name;
newUser.email = request.body.email;
newUser.pass = request.body.pass;
newUser.position = request.body.pos;
newUser.phone = request.body.phone;
mongoose.connection.openUri(url);
var myquery = { _id : request.params._id };
console.log("updating...")
User.findByIdAndUpdate(myquery,{$set: newUser},{new: true},function(err, result) {
if(err)
{
throw err;
}
response.json({code: 0 , result});
});

Can't compare MongoDB data with javascript array

I want to compare the data which I got from Mongo to javascript array. I am using lodash to compare. But it always return incorrect result.
var editUser = function(userData, getOutFunction) {
var status = CONSTANTS.NG;
checkExistUser(userData._id).then(function(user) {
if (user !== null) {
var userGroup = JSON.stringify(user.group);
user.group = user.group.map((groupId) => {
return groupId.toString();
});
var removedGroups = _.difference(userGroup, userData.group);
var addedGroups = _.difference(userData.group, userGroup);
console.log('Removed Groups: ', removedGroups);
console.log('Added Groups: ', addedGroups);
} else {
status = CONSTANTS.NG;
logger.debug(DEBUG_CLASS_NAME, "Cannot find object");
if (typeof(getOutFunction) !== 'undefined') {
getOutFunction(status, null);
} else {
NO_CALLBACK();
}
}
}).catch(function() {
console.log('Promise is error');
});
var checkExistUser = function(userId) {
return new Promise(function(resolve, reject) {
UserDAO.findById(userId, function(err, user) {
if (err) {
logger.debug(DEBUG_CLASS_NAME, {
name: err.name,
code: err.code,
message: err.message,
method: "checkExist"
});
resolve(null);
} else {
resolve(user);
}
});
});
}
For example:When I try to input value for lodash difference function
var user.group = ["58b8da67d585113517fed34e","58b8da6ed585113517fed34f"];
var userData.group = [ '58b8da67d585113517fed34e' ];
I want lodash difference return below result:
Removed Groups: ['58b8da6ed585113517fed34f']
Added Groups: []
However, the function gave me the result like:
Removed Groups: []
Added Groups: [ '58b8da67d585113517fed34e' ]
Can anyone help me in this case?
I will do appreciate it.
I have had this issue as well, the result from mongodb is an ObjectId type so you can compare the someObjectId.toString() value with your array of strings, or you could use
someObjectId.equals(stringOrObjectIdValue)
However, if you want to keep using lodash functions you will either have to force both arrays to strings or to ObjectIds before passing them into the function.

Mongodb query doesn't work

In my image sharing application you can upload images and create albums. When you delete an image from the site it shall also be deleted in the albums (the ones that has got the image in it).
Below is the route for deleting an image, and what I really need help with is why the code for deleting the images (imageName and imageId) in the albums below doesn't work.
Thanks in advance!
The models:
var AlbumSchema = new Schema({
title : String,
imageName : [String],
imageId : [String]
});
modelObject.AlbumSchema = AlbumSchema;
modelObject.Album = mongoose.model('Album', AlbumSchema);
-
var BlogPostSchema = new Schema({
name : String,
size : Number,
type : String,
author : ObjectId,
title : String
});
modelObject.Comment = mongoose.model('Comment', CommentSchema);
modelObject.BlogPost = mongoose.model('BlogPost', BlogPostSchema);
The part that doesn't work in the code below is the following:
albums[i].imageName.remove(j);
albums[i].imageId.remove(j);
albums[i].save(function (err){
if (err) {
console.log(err);
// do something
}
});
Full code:
app.get('/blog/delete/:id', function(req, res){
model.BlogPost.findById(req.params.id, function (err, blog){
var theImage = blog.name;
var query = albumModel.Album.find( { imageName:theImage } )
query.exec(function (err, albums) {
if (!albums) {
blog.remove(function(err) {
console.log(err);
// do something
});
res.redirect('/blogs');
}
else {
for (var i = 0; i < albums.length; i++) {
for (var j = 0; j< albums[i].imageName.length; j++){
if (theImage == albums[i].imageName[j]){
albums[i].imageName.remove(j);
albums[i].imageId.remove(j);
albums[i].save(function (err){
if (err) {
console.log(err);
// do something
}
});
}
}
}
}
blog.remove(function(err) {
console.log(err);
// do something
});
res.redirect('/blogs');
});
});
});
JavaScript arrays don't have a remove method so I would expect your code may be crashing. You should be using code like albums[i].imageName.splice(j, 1); instead.

Resources