Store mongoDB document data as a variable - javascript

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.

Related

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

Using Multiple FindOne in Mongodb

I am trying to extend the amount of fields that our API is returning. Right now the API is returning the student info by using find, as well as adding some information of the projects by getting the student info and using findOne to get the info about the project that the student is currently registered to.
I am trying to add some information about the course by using the same logic that I used to get the project information.
So I used the same findOne function that I was using for Projects and my logic is the following.
I created a variable where I can save the courseID and then I will put the contents of that variable in the temp object that sending in a json file.
If I comment out the what I added, the code works perfectly and it returns all the students that I require. However, when I make the additional findOne to get information about the course, it stops returning anything but "{}"
I am going to put a comment on the lines of code that I added, to make it easier to find.
Any sort of help will be highly appreciated!
User.find({
isEnrolled: true,
course: {
$ne: null
}
},
'email pantherID firstName lastName project course',
function(err, users) {
console.log("err, users", err, users);
if (err) {
return res.send(err);
} else if (users) {
var userPromises = [];
users.map(function(user) {
userPromises.push(new Promise(function(resolve, reject) {
///////// Added Code START///////
var courseID;
Course.findOne({
fullName: user.course
}, function(err, course) {
console.log("err, course", err, course);
if (err) {
reject('')
}
courseID = course ? course._id : null
//console.log(tempObj)
resolve(tempObj)
}),
///// ADDED CODE END //////
Project.findOne({
title: user.project
}, function(err, proj) {
console.log("err, proj", err, proj);
if (err) {
reject('')
}
//Course ID, Semester, Semester ID
//map to custom object for MJ
var tempObj = {
email: user.email,
id: user.pantherID,
firstName: user.firstName,
lastName: user.lastName,
middle: null,
valid: true,
projectTitle: user.project,
projectId: proj ? proj._id : null,
course: user.course,
courseId: courseID
}
//console.log(tempObj)
resolve(tempObj)
})
}))
})
//async wait and set
Promise.all(userPromises).then(function(results) {
res.json(results)
}).catch(function(err) {
res.send(err)
})
}
})
using promise could be bit tedious, try using async, this is how i would have done it.
// Make sure User, Course & Project models are required.
const async = require('async');
let getUsers = (cb) => {
Users.find({
isEnrolled: true,
course: {
$ne: null
}
}, 'email pantherID firstName lastName project course', (err, users) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findCourse = (users, cb) => {
async.each(users, (user, ecb) => {
Project.findOne({title: user.project})
.exec((err, project) => {
if (!err) {
users[users.indexOf(user)].projectId = project._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findProject = (users, cb) => {
async.each(users, (user, ecb) => {
Course.findOne({fullName: user.course})
.exec((err, course) => {
if (!err) {
users[users.indexOf(user)].courseId = course._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
// This part of the code belongs at the route scope
async.waterfall([
getUsers,
findCourse,
findProject
], (err, result) => {
if (!err) {
res.send(result);
} else {
return res.send(err);
}
});
Hope this gives better insight on how you could go about with multiple IO transactions on the same request.

How do you access an existing value inside mongoose query?

Pretty much I have built an application for users to receive points and every 10 points they should receive a trophy. RewardPoints are integer and Trophies is an array. I want to increment the rewardPoints when user pays and at the same time do the validation to push a trophy if existing points after the update are 10 or 20 or 30 etc. I've somehow made it using normal js without the push(simply using math.floor() to set the numoftrophies) inside the .exec() function but i have other problems occurring on user.save(). I want to transform this:
User.findById(req.body.userID).exec(function(err, user){
if (err){throw err;}
user.rewardPoints = user.rewardPoints + 1;
let trophyNumbers = Math.floor(user.rewardPoints / 10)
user.trophies = trophyNumbers;
user.save();
})
to something like this:
User.update({ _id: req.body.userID },
{
$inc: { rewardPoints: 1 },
$push: {
trophies: {
trophy: new Date(),
trophyNum: Math.floor(rewardPoints / 10)
}
}
})
.exec(function (err, res) {
if (err) { throw err; }
//trophy must be added every 10 points
console.log('points saved');
});
How do i access the existing rewardPoints inside $push of trophies? If anyone could help I'd be really appreciative.
try this:
User.findById(req.body.userID).exec(function (err, user) {
if (err) { throw err; }
let newRewardPts = user.rewardPoints + 1;
User.update({ _id: req.body.userID },
{
$inc: { rewardPoints: 1 },
$addToSet: {
trophy: new Date(),
trophyNum: Math.floor(newRewardPts / 10)
}
})
.exec(function (err, res) {
if (err) { throw err; }
//trophy must be added every 10 points
console.log('points saved');
});
})

Mongoose, Select a specific field with find

I'm trying to select only a specific field with
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
But in my json response i'm receiving also the _id, my document schema only has two fiels, _id and name
[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]
Why???
The _id field is always present unless you explicitly exclude it. Do so using the - syntax:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Or explicitly via an object:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
There is a shorter way of doing this now:
exports.someValue = function(req, res, next) {
//query with mongoose
dbSchemas.SomeValue.find({}, 'name', function(err, someValue){
if(err) return next(err);
res.send(someValue);
});
//this eliminates the .select() and .exec() methods
};
In case you want most of the Schema fields and want to omit only a few, you can prefix the field name with a - (minus sign). For ex "-name" in the second argument will not include name field in the doc whereas the example given here will have only the name field in the returned docs.
There's a better way to handle it using Native MongoDB code in Mongoose.
exports.getUsers = function(req, res, next) {
var usersProjection = {
__v: false,
_id: false
};
User.find({}, usersProjection, function (err, users) {
if (err) return next(err);
res.json(users);
});
}
http://docs.mongodb.org/manual/reference/method/db.collection.find/
Note:
var usersProjection
The list of objects listed here will not be returned / printed.
Tip: 0 means ignore & 1 means show.
Example 1:
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
Example 2:
User.findById(id).select("_id, isActive").then(...)
Example 3:
User.findById(id).select({ _id: 1, isActive: 1, name: 1, createdAt: 0 }).then(...)
DB Data
[
{
"_id": "70001",
"name": "peter"
},
{
"_id": "70002",
"name": "john"
},
{
"_id": "70003",
"name": "joseph"
}
]
Query
db.collection.find({},
{
"_id": 0,
"name": 1
}).exec((Result)=>{
console.log(Result);
})
Output:
[
{
"name": "peter"
},
{
"name": "john"
},
{
"name": "joseph"
}
]
Working sample playground
link
Exclude
Below code will retrieve all fields other than password within each document:
const users = await UserModel.find({}, {
password: 0
});
console.log(users);
Output
[
{
"_id": "5dd3fb12b40da214026e0658",
"email": "example#example.com"
}
]
Include
Below code will only retrieve email field within each document:
const users = await UserModel.find({}, {
email: 1
});
console.log(users);
Output
[
{
"email": "example#example.com"
}
]
The precise way to do this is it to use .project() cursor method with the new mongodb and nodejs driver.
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
I found a really good option in mongoose that uses distinct returns array all of a specific field in document.
User.find({}).distinct('email').then((err, emails) => { // do something })

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

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.

Categories

Resources