MongoDB: first argument must be string or Buffer? - javascript

I am trying to write all the documents in a mongoDB collection to my web site. My code:
mongoClient.connect('mongodb://localhost:27017/database', function(err, db) {
if (err) throw err
var cursor = db.collection("Users").find();
while(cursor.hasNext()){
res.write(cursor.next())
}
res.end()
But I get the error first argument must be a string or buffer. Why is that? How can I parse the above data into a string then?

Try the following snippet, Am assuming resp is http response.
mongoClient.connect('mongodb://localhost:27017/database', function(err, db)
{
if (err) throw err
console.log("Connected successfully to server");
db.collection("Users").find({}).toArray(function(err, dbres) {
console.log("select : ", dbres);
db.close();
resp.writeHead(200, { "Content-Type": "application/json"});
resp.write(JSON.stringify(dbres));
resp.end();
});
}

Related

getting empty object in postman for get request from node js with mongodb database

I am using MEAN stack for crud operation where I am testing my backend routes for that I am using postman.
When I am trying to get the data from database I am getting an empty array in response and in nodejs console. help me for the same
router.get('/getUser',async(req,res)=>{
try {
await client.connect(url,{ useUnifiedTopology: true },async(err,db)=>{
if(err) throw err;
let dbo = db.db("company");
console.log("connected to database");
let fetchedUsers = await dbo.collection("employee").find({}).toArray((err,result)=>{
if(err) throw err;
console.log(result);
res.json(result);
db.close();
});
// await fetchedUsers.forEach((user)=>{
// console.log(user);
// });
// await res.json(fetchedUsers);
// await db.close();
});
} catch (error) {
res.send("Something happened" + " "+error);
}

Why isnt my mongoDB update-function exited after successfully updating the document?

I tried to write a function that connects to my MongoDB and updates a specific document in a given collection. The updating itself works as expected. However, when I run the code, it doenst end after updating the document. Do you know why? Any help is very much appreciated.
function updateColletion(payload) {
mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true},
function(err) {
if (err) throw err;
console.log('Successfully connected');
MongoDBModel.findByIdAndUpdate('exampleDocumentID', {
payload
},
{upsert: true},
function(err) {
if (err) throw err;
console.log("TrackerRegex updated.")
});
});
};
const updatePayload = {exampleKey: exampleVar};
updateTrackerRegex(updatePayload);

Nodejs querying single data instead of all from mongodb collection

I am trying to fetch data from mongodb's collection. My code is executing only single row data in json format. But when I console log my data I can see all the row data.
const mongoose = require('mongoose');
const AllMinisters = require('../models/allMinisters');
var db;
var mongodb = require("mongodb");
// Initialize connection once
mongoose.connect("******", { useNewUrlParser: true }, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
exports.getAllMinisters = (req,res,next)=>{
db.collection("users").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
var response = {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: doc
}
res.end(JSON.stringify(response));
}
});
});
};
This output in JSON as
However the console report shows all
How can I show all row data in JSON
You have docs.each in your code that will iterate over all the doc you get from the find() query (which is an array) and inside that each block you are sending the response i.e, res.end(JSON.stringify(response));, which executes immediately for the first record and hence you get a single object as a response instead of array.
To return the array you need to put res.end(JSON.stringify(response)); outside the each() loop with toArray function. You can even remove the each() loop if that is not required. So, your code will be something like:
exports.getAllMinisters = (req, res, next)=>{
db.collection('users').find({}).toArray(function (err, docs) {
if (err) {return next(err);}
docs.each(function (err, doc) {
if (doc) {
//code for single doc
console.log(doc);
}
});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(docs));
});
};

sql syntax error with nodejs

I'm trying to get the results pulled from the API inserted into a database. It returns a SQL error when the program is run. It seems I'm not having this sent in the right syntax and I cant seem to to get it to do so. Is there a better way to do this?
var request = require('request');
var mysql = require('mysql');
var replace = require ('Regexp')
var url = 'https://api.nicehash.com/api?method=stats.provider.workers&addr=3Hwm6i8aefzHhJTbEGtSJeR6tZCJXqY7EN';
//connect to database
var con = mysql.createConnection({
host: 'localhost',
user: 'xxxxx',
password: 'xxxxx',
database: 'xxxxx',
table: 'workerstats'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
const requestHandler = (request, response) => {
response.end(workerstats)
}
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
}
else if (res.statusCode !== 200)
{
console.log('Status:', res.statusCode);
}
else {(!err && data && data.result && data.result.workers)
var workerstats = JSON.stringify(data.result.workers);
var wsclean = workerstats.replace(/[&\/\\#+()$~%'*?<>{}]/g,'')
.replace(/"a":/g,'');
};
console.log(wsclean);
var sql = "INSERT INTO 'workerstats' (workers, accepted, uptime, xnsub, difficulty, zone, algo) ?", wsclean;
con.query(sql, [workerstats], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
}
);
})
EDIT: Okay so after hours of tinkering, I 'think' I've made progress, but that silly A: has got me again. Its viewing as an object, and SQL is rejecting it. Though I thought (Though obviously improperly) I converted it to string. This is the amended code. Please forgive the formatting, it wasnt playing nice.
request.get({
url: url,
json: true,
headers: { 'User-Agent': 'request' }
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
}
else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
}
else {
(!err && data && data.result)
var data = JSON.parse(data.result);
var responseJson = JSON.stringify(data.response);
var query = connection.query('INSERT INTO table SET column=?', responseJson, function (err, result) {
if (err) throw err;
console.log('data inserted');
});
}
});
It returns the following error:
undefined:1
[object Object]
SyntaxError: unexpected token o in JSON at postion 1
Awesome. So somewhere I did something stupid, or improperly. In the raw API that object Object appears like: {"a":"158.01"} - How do I convert that to a string, when I thought I already did? Id also like to eliminate the 'a' and the ':' entirely as im not sure how to process that into SQL and its unneeded information.
When you setup json: true in the request option, You no longer have to perform JSON.parse(data.result), you directly access the data as object. Therefore the error, because JSON.parse({ a: 1}) call the toString method, and the result [object Object] its not valid JSON.
Note: You convert the data.result.workers to a string. I think you should leave it as an array for it to work.
con.query(sql, data.result.workers, function (err, result)

MongoDB is connecting but does not update

I have not used MongoDB with NodeJS for a while so I am a bit rusty. I have written the code below and it is connecting properly but for some reason, the values are not updating. Can someone tell me what is wrong with my code?
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to Mongodb: Log Request (token and sender)");
var query = {sender:senderThatAsked};
db.collection("requestFrom").updateOne(
query,
{$set:{date: new Date(Date.now()).toISOString()}},
{$setOnInsert: {
token:tokenUsed,
date: new Date(Date.now()).toISOString(),
count: 0,
sender:senderThatAsked }},
{upsert: true}, function(err,res){
if (err) throw err;
console.log('The request has been logged! Now Finding...');
db.close();
});
});
Thanks in advance.
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to Mongodb: Log Request (token and sender)");
var query = {sender:senderThatAsked};
db.collection("requestFrom").updateOne(
query,
{
$set:{date: new Date(Date.now()).toISOString()},
$setOnInsert: {
token:tokenUsed,
count: 0,
sender:senderThatAsked
}
},
{upsert: true}, function(err,res){
if (err) throw err;
console.log('The request has been logged! Now Finding...');
db.close();
});
});
put $set and $setOnInsert in one object please

Categories

Resources