making the output of "find" using mongodb with nodejs look better - javascript

I am using a function to find clients from my mongodb database using node js.
In my query I'm trying to get the function to output the data without the "_id"
but it's not working.
function findClient(Fname,res){
let query = {name:Fname}
dbo.collection("clients")
.find(query,{ _id: 0,name: 1 ,last: 1, age:1})
.toArray(function(err, result) {
if (err) throw err;
result = JSON.stringify(result)
res.render(`./pages/findRes`,{data:result})
console.log(result)
});
}

You don't need to use toArray here.
function findClient(Fname, res) {
let query = { name: Fname }
dbo.collection("clients").find(query, { _id: 0, name: 1, last: 1, age: 1 }, function (err, result) {
if (err) throw err;
result = JSON.stringify(result)
res.render(`./pages/findRes`, { data: result })
console.log(result)
});
}
Basic example here: https://mongoplayground.net/p/WzCaITFhCHM
This should work.

Related

How to access variable in a function expression nodejs [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Is there a way to get the contents of variable data outside the function. I am so stuck, looked various forums in stackoverflow and but failed. I am trying to retrieve data from mongoose model and push those results into an array results and when i print results array, i get empty array .
var results = []
Model.find({firstName:name}, function(err,data){
if(err)
throw err;
data.forEach(function(element) {
console.log(element);
results.push(element);
});
});
console.log(results) --> []
But when i try to print the data inside the ForEach, I am was get the results, listed below.
0 => { _id: 5dc9953a2168993711903698,
id: 763,
firstName: 'Deepak',
lastName: 'Kalra',
image_id: 'No',
logged: false,
__v: 0
}
1 => {
_id: 5dc995546f0f88372080ea36,
id: 511,
firstName: 'Deepak',
lastName: 'Kalra',
image_id: 'No',
logged: false,
__v: 0
}
Entire code
alexa.intent("FirstName", {
"slots": { "name": "AMAZON.FIRST_NAME" },
"utterances": [
"sure {-|name}","{-|name}","my name is {-|name}"
]
},
function(request, response) {
var name = 'Deepak';
try {
var results = await Model.find({firstName:name});
console.log(results)
} catch (error) {
// Handle error.
}
// Model.find({firstName:name}, function(err,data){
// if(err)
// throw err;
// data.forEach(function(element) {
// console.log(element);
// results.push(element);
// });
// });
console.log(results);
});
Is there any solution to fix it. please help me
Because, console.log(results) executed before Model.find was finished.
Two things you can do here:
Put console.log(results) inside the callback.
Use async/await to get similar behaviour.
Example (callback):
Model.find({firstName:name}, function(err,data){
if(err)
throw err;
console.log(data); // data is already an array
});
Example (async/await):
try {
var results = await Model.find({ firstName: name });
console.log(results)
} catch (error) {
// Handle error.
}
Model.find already returns an array of document, so you don't have to run a loop to push them into an array.
UPDATED
alexa.intent("FirstName", {
"slots": { "name": "AMAZON.FIRST_NAME" },
"utterances": [
"sure {-|name}", "{-|name}", "my name is {-|name}"
]
},
async function (request, response) {
var name = 'Deepak';
try {
var results = await Model.find({ firstName: name });
console.log(results)
} catch (error) {
// Handle error.
}
});
Notice the async in front of function.

Get json data from microsoft sql server and store in variable to use in vuejs v-for attribute

I am developing a full stack application. And my front-end development is ready. I am using vuejs to display array on screen. And now I need to get that array from sql server using nodejs. I really dont know about asynchronous functions, http requests and tons of server based knowledges. Just wanted to get a array without any knowledge exploring.
It is my node module which is set for get data or insert data into mssql server.
var dbConfig = {
server: "localhost\\MSSQLSERVER",
database: "sample",
user: 'sa',
password:'deegii2001060108',
port: 1433
};
var result;
exports.dbcontext=function(engine, config){
const sql = require('mssql')
return new Promise(function(resolve, reject) {
var conn = sql.connect(config, function(err) {
if(err) {
reject(err);
} else {
sql.query(engine, function(err, recordsets,returnValue, affected) {
if(err) {
reject(error);
} else {
result = recordsets;
resolve(recordsets);
conn.close();
}
})
}
})
})
}
exports.dbcontext('select * from tblGender', dbConfig).then(recordset=>{console.log(recordset)});
console.log('result',result);
in console:
result undefined
{
recordsets: [ [ [Object], [Object], [Object], [Object], [Object] ] ],
recordset:[
{ id: 1, gender: 'male' },
{ id: 2, gender: 'female' },
{ id: 3, gender: 'unknown' },
{ id: 4, gender: 'aertq' },
{ id: 5, gender: 'from vscode' } ],
output: {},
rowsAffected: [ 5 ] } //i wanted to store recordset into my global result var outside of function
}
exports.dbcontext(... //connection function
result = recordsets; /*the result variable is not changed but i want to
store recordsets in global variable outside of the function*/
...}
//Unexpected result:
console.log(result) // undefined
//Expected result:
console.log(result) // an array consists of objects
var express = require('express');
var app = express();
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'deegii2001060108',
server: 'localhost\\MSSQLSERVER',
database: 'sample'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from tblGender', function (err, result) {
if (err) console.log(err)
// send records as a response
console.log(JSON.stringify(result));
});
});
var mysql = require('mysql');
var result;
var con = mysql.createConnection({
host: "localhost\\MSSQLSERVER",
user: "sa",
password: "deegii2001060108",
database: "sample"
});
con.connect(function(err) {
if (err) throw err;
con.query("select * from tblGender", function (err, data, fields) {
if (err) throw err;
result = data;
});
console.log(json.stringify(result));
});

Why don't changes made to a global variable in a foreach function callback reflect oustide the callback

I'm trying to retrieve some documents from mongoDB atlas, below is the code:
get('/:page/bucket_names', (req, res) => {
var page = req.params.page;
var pageBuckets = [];
MongoClient.connect(uri, (err, client) => {
if (err) res.send('error:' + err);
const db = client.db("cms");
db.collection(page).find({ $or: [{ type: 'single' }, { type: 'carousel' }, { type: 'freelist' }] }, (err, result) => {
if (err) res.send('error');
else {
result.forEach(el => {
pageBuckets.push(el);
console.log(pageBuckets) //1
})
console.log(pageBuckets) //2
}
})
client.close();
})
})
The first console.log outputs the updated pageBuckets array but the second console.log outputs an empty array. I'm not able to understand what the problem is.
Turns out the 2nd console.log was getting executed before the foreach loop , so fixed it with the below code:
result.forEach(el =>{
pageBuckets.push(el);
console.log(pageBuckets) //1
}).then(() =>{
console.log(pageBuckets); //2
})

Store mongoDB document data as a variable

I have a node.js app where I want to send data from mongoDB over socket.io where I can have the data display on a client but I can't figure out how to send it over the socket, the code is as follow
MongoClient.connect("mongodb://localhost:27017/", function (err, db) {
if (err) throw err;
var dbo = db.db("database1");
dbo.collection("items").find({
iname: search,
qty: qValue
}, {
_id: 0
}).toArray(function (err, result) {
if (err) throw err;
if ({ $eq: "yesView"}) {
console.log("Find Succsessful;");
if ({ $eq: "notRec"}) {
socket.emit('findSuccess', (result[2]), (result[3]))
}
But on the client when i have
socket.on('findSuccess', function (view, rec) {
viewVal = view;
recVal = rec;
});
both viewVal and recVal are equal to null and when I do console.log(result); if i put in cd for the search and 4 for the qValue it has
[ { iname: 'cd',
qty: '4',
view: 'yesView',
rec: 'notRec' } ]
My question how do i get viewVal on client to equal what view is in the document?
As #gaetanoM said, it works if you change result[2] to result[0].view, I'm only answering this because I don't want to leave it unanswered.

how to get key value from json result in node js

how can I get specify email and its value only, from JSON array result which should be like=>only( email: abc#gmail.com)
here is my code:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
this is the result which i am getting in console
[ { _id: 5a9f8849fc49ca1ff4aee3dc,
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' } ]
This is a simple JavaScript:
var res = [
{ _id: '5a9f8849fc49ca1ff4aee3dc',
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3dd',
email: 'abcd#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3de',
email: 'abcde#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' }
];
var finalRes = res.map(({email}) => ({email}));
console.log(finalRes);
You can use reduce or map on your array:
Using reduce
reducedResults = result.reduce((accumulator, current) => {
accumulator.push({ email: current.email });
return accumulator;
}, [])
Using map
mappedResults = result.map((user) => {
return { email: user.email };
})
You could use select method from mongoose api. Basically, you can control with it what will result object contains of its properties. So, your code could look like this:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).select({email: 1, _id: 0}).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
You should get something like this:
[ { email: 'abc#gmail.com'} ]
If you need _id, use this in select {email: 1, _id: 1}

Categories

Resources