In all tutorials I searched the web, they print the rows/result using console.log the from the mysql query. In my case, I want to store that value to manipulate it in a function. The problem is that node doesn't wait. Can you help me in catching the rows in such example? How can I store the rows in a variable?
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result) {
if (err) throw err;
console.log(result);
});
});
I tested one of the solutions but I got [] when trying to get result/rows out of the function. I want to use the result in the savedServices: [] see below:
Give a fresh start with a simple project
Follow below commands
mkdir testdb
cd testdb
npm install --save mysql
npm install --save async
Create a test.js file
vim text.js
Now put below code in the test.js file
var mysql = require('mysql');
var async = require('async');
var con = mysql.createConnection({
host: "localhost",
database: "mydb",
user: "user",
password: "pass"
});
var myrows = [];
async.waterfall([
function(callback) {
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = 'select * from users limit 5';
con.query(sql, function (err, result) {
if (err) throw err;
result.forEach(function(item) {
//console.log(item);
myrows.push(item);
});
callback(null, myrows);
});
});
}
],
// optional callback
function(err, myrows) {
console.log("myrows:::");
console.log(myrows);
});
now test the file
node test.js
You should see results like this:
Connected!
Result: [object Object],[object Object],[object Object],[object Object],[object Object]
Hope this helps!
Related
Hello I have issue with MongoDB code, it make some methods like this (image below):
enter image description here
`
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var mysort = { name: 1 };
dbo.collection("customers").find().sort(mysort).toArray(function (err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
`
and when I try read error, it say:
(method) MongoClient.connect(url: string, callback: Callback): void (+3 overloads)
#deprecated — Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance
The signature '(url: string, callback: Callback): void' of 'MongoClient.connect' is deprecated.ts(6387)
mongodb.d.ts(4733, 9): The declaration was marked as deprecated here.
No quick fixes available
I tried reinstall it, or install older version and still same, I do connection same like in documentation.
Tried add (url,{ useUnifiedTopology: true }, and still same
Someone know what can be issue?
Try version 4.0.0
const MongoClient = require('mongodb').MongoClient;
// Connect to the MongoDB server
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
if (err) throw err;
// Get the sample database
const db = client.db('sample');
// Get the collection
const collection = db.collection('test');
// Insert a document
collection.insertOne({ name: 'John', age: 30 }, function(err, result) {
if (err) throw err;
console.log(result);
// Close the connection
client.close();
});
});
Let me know if you still have the same error .
In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});
I have my nodejs lambda function connecting to rds and select data and gives me output in log output. Please help me how to pass parms and get output. My code is attached. My nodejs function connecting to rds but I cannot see mydata in execution result.
var mysql = require('mysql');
exports.handler = (event, context) => {
var con = mysql.createConnection({
host: "testdb.ckwywu.ap-south-1.rds.amazonaws.com",
user: "root",
password: "mypassword",
database: "database",
port: "3306",
// debug: true
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
// var sql = "INSERT INTO users (id, name) VALUES (4, 'dfdd')";
var sql = "select * from database.users";
con.query(sql, function (err, result) {
if (err) throw err;
// console.log("1 record inserted");
console.log(result);
context.succeed("done");
});
});
//callback("sucess");
}
My code looks like this:
#!/bin/env node
var collection = require('mongojs')('test').collection('test');
collection.findOne({}, function(err, doc) {
console.log(err, doc);
});
When I ran this script, it showed:
$ node test.js
null null
But the script didn't quit. I need to "CTRL+C" to quit it. Any body know how to fix it?
[update]
I found that if I use native mongodb instead of mongojs, there's no problem:
#!/bin/env node
var client = require('mongodb');
client.connect('mongodb://127.0.0.1:27017/hatch', function(err, db) {
if (err) throw err;
var collection = db.collection('documents');
collection.find().toArray(function(err, results) {
console.dir(results);
db.close();
});
});
So is it a mongojs issue?
You have to close the db connection
var mongojs = require('mongojs');
var db = mongojs('test');
var collection = db.collection('test');
collection.findOne({}, function(err, doc) {
console.log(err, doc);
db.close();
});
I'm trying to get the result of query but i get the same info in all vars: db, collection and res:
var mongodb = require("mongodb");
var mongoserver = new mongodb.Server("localhost", 27017);
var instance = new mongodb.Db("test", mongoserver);
instance.open(function(err, db)
{
console.log('db:');
console.log(db);
db.collection('kurtsoa', function(err, collection)
{
console.log('collection:');
console.log(collection);
collection.find({}, function(err, res)
{
console.log('res:');
console.log(res);
});
});
});
how i can get the result of "find"?
.find() will return a Cursor object for you to work with. If all you are interested in is getting all the results in an array you can do:
collection.find().toArray(function(err, docs) {
console.log(docs);
});
But you can also iterate the cursor too:
collection.find().each(function(err, doc) {
//called once for each doc returned
});
You can use this:
collection.find().toArray(function(err, docs){
console.log(docs);
)};