Somename Somename -4 years ago 188
Node.js Question

How to keep the node server running?

Locally, when my code is putting some data in mongodb through mongoose, if something is wrong,

(err)
, the error is displayed on the command prompt window used to start the server. And the node server is stopped. Is this what is know as
synchronous
? My code :

User.findOne({id:myid}, function(err, user){
if(err) return done(err);
if(user) return done(null, user);
else{
var newUser = new User();
newUser.name = myname;
newUser.id = myid

newUser.save(function(err){
if(err) throw err;
return done(null, newUser);
});
}
});


With the above code, if there is a duplicate entry i get the error
11000
from mongoose and the server is stopped. Do I need to edit wherever it says
return err
? What do I need to keep the server running with a message sent to the client (Angular) and not logged in the console that crashes the server. I'm fairly new to
MEAN
and still learning. The above code works perfect if the id is not duplicate. [I have the
id
field as
unique
]

Many thanks.

Answer Source

The reason why your app is stopping is you're using throw when an error is returned by save().

That results in an 'uncaughtException' event on the process object which if it has no listener will cause your process to exit.

Typically in Node.js you don't use throw unless the app should stop or the code is synchronous (IE JSON.parse())

You should instead communicate that the error occurred back to the caller following the error first callback convention used throughout Node.js

newUser.save(function(err) {
  if(err)
    return done(err); // Let caller handle error

  return done(null, newUser);
});

To give a more End-to-End example assuming you're using Express to handle requests to the DB from an HTTP Request

const express = require('express');
const app = express();
const bodyParser = require('body-parser);

app.use(bodyParser.json());

const createUser = function(myid, myname, done)
  User.findOne({id:myid}, function(err, user){
    if(err) 
      return done(err);
    if(user) 
      return done(null, user);

    var newUser = new User();
    newUser.name = myname;
    newUser.id = myid

    newUser.save(function(err){
      if(err) 
        return done(err)

      return done(null, newUser);
    });  
  }           
}); 

app.post('/users', function(req, res) => {
  if (!req.body.myid || !req.body.myname)
    return res.status(400).send('missing myid or myname from request body')

  createUser(req.body.myid, req.body.myname, (err, newUser) => {
    if(err)
      return res.status(500).send(err);  // Typically some error handling goes here

     return res.status(201).send(newUser);
  }
});

app.listen(process.env.PORT || 1337, () => { console.log('Listening' )});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download