I am having problem when I pass the node .get to show the result the array wraps the data result.
[
{
"book_id": 1,
"title": "HARRY",
"pages": "123",
"image": ""
}
]
Is there way to make the result show like this without array?
{
"book_id": 1,
"title": "HARRY",
"pages": "123",
"image": ""
}
This is code for node to fetch data from sql.
app.get('/books/:id', function(req, res, next) {
db.get_individual([req.params.id], function(err, individual) {
if(err) res.status(500).send(err);
else res.send(individual);
});
});
This is the Sql query
SELECT * FROM book;
You can send the object at [0]:
res.send(individual[0]);
Related
but i getting all users but by id didnt working
[
{
"firstName": "myname",
"lastName": "notimp",
"email": "myname#gmail.com",
"textbox": "this pc",
"Imgupload_date": "2020-07-13T07:36:44.117Z",
"Image_name": "Screenshot.png",
"id": "1"
},
{
"firstName": "hello",
"lastName": "world",
"email": "helloworld#gmail.com",
"textbox": "this pc",
"Imgupload_date": "2021-07-13T07:36:44.117Z",
"Image_name": "Screenshot 2021-07-13 130641.png",
"id": "2"
}
]
i need only id=1 user
app.get('/api/user', (req, res) => {
console.log('api/user called!!!!!!!')
const databuffer = fs.readFileSync('user.json', 'utf8')
const datajson = databuffer.toString()
const dtafil = JSON.parse(datajson);
res.json(dtafil);
});
by /?...You need to extract data from query parameters.
for example for api/users/?id=1:
app.get('api/users/', async function(req, res) {
let id= req.query.id;
});
If you want to get parameters from the url you need to set up the endpoint to get it.
This part of the expressjs docs explains how to do that.
I have been trying to use an API from https://api.nomics.com/ and I cant seem to use the data inside the JSON object. I want to get the "price" value and display it in the console log but it keeps saying my variable is undefined please assist:
app.post("/", function(req, res) {
request("https://api.nomics.com/v1/currencies/ticker?key=demo-26240835858194712a4f8cc0dc635c7a&ids=BTC&interval=1d&convert=USD&per-page=10&page=1", function(error, response, body) {
var data = JSON.parse(body);
var price = data.price;
console.log(data);
console.log(price);});});
The result I get is:
[ {
"id": "BTC",
"currency": "BTC",
"symbol": "BTC",
"name": "Bitcoin",
"logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg",
"status": "active",
"price": "10609.61844458",
"price_date": "2020-10-07T00:00:00Z",
"price_timestamp": "2020-10-07T08:12:00Z",
"circulating_supply": "18510093",
"max_supply": "21000000",
"market_cap": "196385024104",
"num_exchanges": "361",
"num_pairs": "38888",
"first_candle": "2011-08-18T00:00:00Z",
"first_trade": "2011-08-18T00:00:00Z",
"first_order_book": "2017-01-06T00:00:00Z",
"rank": "1",
"rank_delta": "0",
"high": "19337.69352527",
"high_timestamp": "2017-12-16T00:00:00Z",
"1d": {
"volume": "16456552525.84",
"price_change": "-148.44596940",
"price_change_pct": "-0.0138",
"volume_change": "1509811120.10",
"volume_change_pct": "0.1010",
"market_cap_change": "-2739282102.40",
"market_cap_change_pct": "-0.0138"
} }]
var price is undefined. is it because of the "[]" that is surrounding the JSON object?
Yes it's because the request you are making return an array of objects, so you need to get the first element and on that get the price.
var price = data[0].price;
I am doing a Node.js REST API tutorial. I use Express, Knex.js (0.19.0) and PostgreSQL.
I have two database tables, users:
// user_migration.js
exports.up = function(knex) {
return knex.schema.createTable('users', function(table) {
table
.increments('id')
.primary()
.unsigned();
table.string('firstName');
table
.string('lastName')
.index()
.notNullable();
table
.string('email')
.unique()
.index()
.notNullable();
table.string('password').notNullable();
table.string('role').defaultTo('STAFF');
table.boolean('isActive').defaultTo(false);
table.timestamp('createdAt').defaultTo(knex.fn.now());
table.timestamp('updatedAt').defaultTo(knex.fn.now());
});
};
and posts:
// post_migration.js
exports.up = function(knex) {
return knex.schema.createTable('posts', function(table) {
table
.increments('id')
.primary()
.unsigned();
table.string('title').notNullable();
table.text('body');
table.boolean('published').defaultTo(false);
table
.integer('author')
.unsigned()
.index()
.references('id')
.inTable('users')
.onDelete('SET NULL');
table.timestamp('createdAt').defaultTo(knex.fn.now());
table.timestamp('updatedAt').defaultTo(knex.fn.now());
});
};
I want to make a GET request at http://localhost:8081/users/1/posts to show user.id 1's posts.
// user_get.js
async getPosts(req, res, next) {
try {
// Check if user exists
const user = await this.knex('users')
.where('id', req.params.id)
.first();
// If not, return NOT FOUND status code
if (!user) return next(createError(404, 'User not found'));
/**
* Right here, I am not sure if I am doing it right.
*/
// Get from database and filter
const result = await this.knex('users')
.join('posts', 'posts.author', '=', 'users.id')
.select()
.then(posts => posts.filter(post => post.author === user.id));
// Return OK status code and related posts
res.status(200).send(result);
} catch (error) {
// Return BAD REQUEST status code
return next(createError(400, error);
}
}
What I expected is an array of posts belong to user 1:
[
{
"id": 1,
"title": "Number One Post",
"body": "This is the one body",
"published": true,
"author": 1,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z"
},
{
"id": 2,
"title": "Number Two Post",
"body": "This is two body",
"published": false,
"author": 1,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z"
}
]
But I got like this:
[
{
"id": 1,
"firstName": "Some",
"lastName": "One",
"email": "some#one.com",
"password": "password789",
"role": "STAFF",
"isActive": false,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z",
"title": "Number One Post",
"body": "This is the one body",
"published": true,
"author": 1
},
{
"id": 2,
"firstName": "Some",
"lastName": "One",
"email": "some#one.com",
"password": "password789",
"role": "STAFF",
"isActive": false,
"createdAt": "2019-07-23T09:21:34.285Z",
"updatedAt": "2019-07-23T09:21:34.285Z",
"title": "Number Two Post",
"body": "This is two body",
"published": false,
"author": 1
}
]
How should I query user 1's posts without mashing up with user info?
Please help.
P.S. Also updatedAt in Knex.js does not work correctly. It does not update the timestamp when I update. How do I fix this?
Just drop your join on users in the second query
const result = await this.knex('posts')
.where('posts.author', user.id)
.select()
// Return OK status code and related posts
res.status(200).send(result);
I have collection named "listing" with fields such as metadata and status. metadata is a object containing user object inside and status is a string.
The structure looks like this,
{ "status": "Active", "metadata": {
"user": {
"urlProfile": "",
"averageRating": 5,
"reviewCount": 2,
"userId": "1244324"
} } }
Now the status field have values such as "Active" and "Inactive". I need to group by those status and filter by the userId. so i have a function inside the helper as follows,
query: function (model, conditon, options) {
console.log(conditon, options);
return new Promise(function (resolve, reject) {
options = options || {};
model.find(conditon, {}, options).exec(function (error, data) {
if (error) {
reject(error);
}
resolve(data);
})
})
}
Question is how can i pass the group by along with the user id and query the data needed. Right now my querying part looks like this,
return dbService.query(sellerModel, {
'metadata.user.userId': userIdRetrieved
}, {});
how can i pass the group by condition? i looked for sample, did not find any solution till now.
Sample Collection
Expected Output:
[{
"Status": "Active",
"Results": {
"user": {
"urlProfile": "",
"averageRating": 5,
"reviewCount": 2,
"userId": "1244324"
}
}
}
,
{
"Status": "InActive",
"Results": {
"user": {
"urlProfile": "",
"averageRating": 5,
"reviewCount": 2,
"userId": "1244324"
}
}
}]
To get the desired output, you would need to use the aggregate method since it offers the operators which allow you to aggregate the documents and return the said result.
Consider constructing a pipeline that consists of a $group stage, whereby you aggregate the average rating via the $avg accumulator, the reviewCount with $sum and the other fields in the group using $first or $last. Your group by key is a subdocument with two fields Status and userId.
A final $project step would allow you to reshape the output from the above group aggregates to the desired form and the aggregate() method returns a query which you can then call exec() to get a Promise.
To explain the above framework, follow this example:
query: function (model, conditon, options) {
console.log(conditon, options);
options = options || {};
return model.aggregate([
{ "$match": conditon },
{
"$group": {
"_id": {
"Status": "$status",
"userId": "$metadata.user.userId"
},
"urlProfile": { "$first": "$metadata.user.urlProfile" },
"averageRating": { "$avg": "$metadata.user.averageRating" },
"reviewCount": { "$sum": "$metadata.user.reviewCount" }
}
},
{
"$project": {
"_id": 0,
"Status": "$_id.Status",
"Results": {
"user": {
"averageRating": "$averageRating",
"reviewCount": "$reviewCount",
"userId": "$_id.userId"
}
}
}
}
]).exec();
}
I've having trouble removing a item from the upload [] object.
The below represents a User, keys[] represents a key for which file uploads get associated with, and uploads[] are files beneath that key. These are all documents embedded within the User model. I realize now I'd have been way better off using references but I am stuck with this for now. Here is the function I'm using right now to find the uploads item,
______________THIS IS MY CURRENT FUNCTION_____________________
I'll be honest I am using async and I don't exactly understand it well. Is there a different async function or way to lookup these items in mongo that would work better?
Current issues: 1) This will continue looping through until the end even after it finds the correct items. 2) How can I delete the upload item?
exports.getApiDelete = function (req, res, next) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
console.log("User ID found: "+ user._id);
//loop though user keys
async.forEach(user.profile.keys, function(item, callback) {
//verify key exists
if(item.key==req.params.scriptkey){console.log("KEY FOUND")};
async.forEach(item.uploads, function(item, callback) {
//verify file exits
console.log(req.params.file_id);
if(item._id == req.params.file_id){
// DELETE FUNCTION HERE?
};
}, function(err){
console.log('Error during async lookup: '+err);
});
}, function(err){
console.log('Error during async lookup: '+err);
});
});
};
______________________________THIS MY USER MODEL_____________________
{
"__v": 19,
"_id": {
"$oid": "53c812c4e75ab0b013f3c6bc"
},
"email": "fake#mailinator.com",
"password": "fake",
"profile": {
"gender": "",
"keys": [
{
"_id": {
"$oid": "53c8130ae75ab0b013f3c6bd"
},
"status": false,
"iteration": 0,
"created": {
"$date": "2014-07-17T18:16:42.568Z"
},
"uploads": [],
"description": "This is being run from my Windows Desktop.",
"location": "Front Row",
"name": "fake_Desktop",
"key": "80f94c80-0dde-11e4-ae14-43922f7b8f23"
},
{
"_id": {
"$oid": "53c814ade75ab0b013f3c6be"
},
"created": {
"$date": "2014-07-17T18:23:41.777Z"
},
"description": "Windows VM test.",
"iteration": 12,
"key": "7ad78410-0ddf-11e4-ae14-43922f7b8f23",
"location": "Back Right",
"name": "fake2_Desktop",
"status": false,
"uploads": [
{
"_id": {
"$oid": "53c81517e75ab0b013f3c6bf"
},
"ip": "10.0.1.156",
"fname": "hklm_1.txt",
"iteration": 1,
"created": {
"$date": "2014-07-17T18:25:27.241Z"
},
"filepath": "script_uploads/7ad78410-0ddf-11e4-ae14-43922f7b8f23_1_hklm_1.txt"
},
{
"_id": {
"$oid": "53c8151ae75ab0b013f3c6c0"
},
"ip": "10.0.1.156",
"fname": "hklm_1.txt",
"iteration": 2,
"created": {
"$date": "2014-07-17T18:25:30.634Z"
},
"filepath": "script_uploads/7ad78410-0ddf-11e4-ae14-43922f7b8f23_2_hklm_1.txt"
}
]
}
}
You want to remove only from array? If yes, use
for(var i =0, j = item.uploads.length; i < j; i++) {
//verify file exits
console.log(req.params.file_id);
if(item.uploads[i]._id == req.params.file_id){
item.uploads.slice(i, 1);
};
And at the end use: user.save(function(err){});
If there is anything you want to delete from file system, use:
fs = require('fs');
fs.unlink( FILE PATH , function(err) {
console.log(err);
});
Also you don't really need async version of forEach, cause User.findById is asynchronous itself and whole process goes on background.
This will continue looping through until the end even after it finds
the correct items.
There is no "break" for async.forEach. So if you don't want to do unwanted process, use for as I did and append a break point.
There is no async call inside your loops, so you don't need async.forEach(). Using javascript native loops would be just fine:
exports.getApiDelete = function (req, res, next) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
console.log("User ID found: "+ user._id);
user.profile.keys.forEach(function(el) {
if(el.key==req.params.scriptkey){console.log("KEY FOUND");}
el.uplaods.forEach(function(item) {
console.log(req.params.file_id);
if(item._id == req.params.file_id){
// DELETE FUNCTION HERE?
}
});
});
});
};