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

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

Related

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

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

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

HTTP Put error when updating array: No matching document found. has no method 'send'

I seem to be having issues performing HTTP Put requests inside an array in AngularJS and ExpressJS. The issue is, when I call the HTTP Put the first time, everything works correctly. However, when I try to call a second time, it doesn't work. The following is my attempt:
When I click a button, I call perform the following HTTP Put Request:
$scope.currentUser.eventsAttending.push(event.eventName);
$http.put('/api/users/' + $scope.currentUser._id, $scope.currentUser)
.success(function(data){
console.log("Success. User " + $scope.currentUser.name);
});
Here is my User schema/model in User.model.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.model');
var UserSchema = new Schema({
name: String,
...
eventsAttending: [{ type: String, ref: 'Event'}]
});
I route the HTTP Put Request as so in index.js:
router.put('/:id', controller.update);
And here is my actual HTTP Put function called controller.update in User.controller.js:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(err); }
if(!user) { return res.send(404); }
var updated = _.merge(user, req.body);
updated.markModified('eventsAttending');
updated.save(function (err) {
if (err) { return handleError(err);}
return res.json(200, user);
});
});
};
...
function handleError(res, err) {
console.log("Error: ", err);
return res.send(500, err);
}
On the second time where I try to call the HTTP Put function (exports.update above), I always get an error in Mongoose that says:
TypeError: Object VersionError: No matching document found. has no method 'send'
at handleError (/Users/schan/test/go-v2/server/api/user/user.controller.js:131:14)
at Promise.<anonymous> (/Users/schan/test/go-v2/server/api/user/user.controller.js:43:25)
The error is basically where I call the if(err) return { handleError(err); } in the HTTP Put function and when I print out the error, I get Error undefined. I'm honestly unsure on how to debug this or what I may be doing wrong. Can anyone point me in the right direction? If so that would be great! Thanks.
You're not passing res to handleError(). Change instances of handleError(err); to handleError(res, err);

Categories

Resources