MongoDB is connecting but does not update - javascript

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

Related

Node js in not saving data in MySql database

I have the following code. When i execute it, i get
Database connected successfully! 1 record inserted. But it saves no data in MySql database.
Im pretty sure my code is correct, but do someone has any tip or advice?
var mysql = require('mysql');
var dbconn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "assessment"
});
dbconn.connect(function(err) {
if (err) throw err;
console.log("Database connected successfully!");
var sqlquery = "INSERT INTO users (username,password) VALUES ('john', 'jmpleom')";
dbconn.query(sqlquery, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record inserted");
});
});
Have you tried committing the data to the database? As a failsafe from unfinished queries, databases will rollback any records to their original state if the data is not committed to the database.
After your insert query, try it out. Based on your code it might look something like this:
dbconn.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
To save or commit data you have to end the connection like this:
dbconn.connect(function(err) {
if (err) throw err;
console.log("Database connected successfully!");
var sqlquery = "INSERT INTO users (username,password) VALUES('john','jmpleom')";
dbconn.query(sqlquery, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record inserted");
dbconn.end(); //like this
});

Connexion lost after exactly 1 minut / 60 seconds of execution

I have a web server run by node.js
It uses Express, Socket.io, and MySQL
I use socket.io to transmit data from client to server, and also to call queries.
After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.
SQL part in the index.js file:
// SQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
//Socket.io
var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {
// Select
socket.on("recherche", function(data) {
if (err) throw err;
con.query("SELECT * FROM ..", function (err, result, fields) {
if (err) throw err;
socket.emit("...", {data: result});
});
});
// Insert into
socket.on("...", function(data) {
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO ... VALUES (...)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
Everything is working just fine for 60 second after start the server.
Then, I have this error message in the nodejs console:
C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
Thank you in advance to read my question :D
connection = mysql.createConnection(db_config); // Recreate the connection, since
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect();
} else {
throw err;
}
});

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

MongoDB: first argument must be string or Buffer?

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

Show Error if Duplicate found in ensureIndex MongoDB Node

I have successfully stopped duplicate entries in MongoDB Database, But my issue is whenever a duplicate entry called, it was not returning any error and just stopping the node server
How to throw any custom error like res.send('duplicate entry')..
i am using forever start server.js for non stop server.
Here below the code for my issue..
router.route('/new_order')
.post(function(req, res, next){
var order_no = req.body.order_no;
var origin_port = req.body.origin_port;
var destination_port = req.body.destination_port;
var expected_date = req.body.expected_date;
var status = 0;
var item = {
order_no: order_no,
origin_port: origin_port,
destination_port: destination_port,
expected_date: expected_date,
status: status
};
var url = 'mongodb://localhost:27017/transport_main';
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err){
db.collection('orders').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('New Order Insterted');
db.close();
res.send('true');
});
});
});
});
Thanks in advance
Add the following:
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err){
if(err) return res.send("You are already registered");...
Solved This issue
11000 is the Duplicate error code which calls while trying to insert. Not while ensureIndex.
ensureIndex was just checking the index created or not, if not it will re-create for us.
important : remove "assert.equal(null, err)" while attempting to insert.
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err, result){
db.collection('orders').insertOne(item, function(err, result){
console.log(err);
if (err) {
if (err.code == 11000) {
res.end('Duplicate Entry Found');
}
}
console.log('New Order Insterted');
db.close();
res.send('true');
});
});
});

Categories

Resources