Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stuck on API creation #47

Open
mikevarela opened this issue Oct 10, 2016 · 4 comments
Open

Stuck on API creation #47

mikevarela opened this issue Oct 10, 2016 · 4 comments

Comments

@mikevarela
Copy link

Fisrt, bought and downloaded PDF (Oct 8th 2016)

The newer versions of mongoose caused a break in code.

However,

I'm stuck now trying to figure out why I can't post a user (create) or get someone. I've decided to use MLAB and I've created a database called 'meanmachinebook'

I know that you created a database with an odd name in the book, and you don't elude to creating any collections, like User, user or users.... so not sure how to post or get from this MLAB database.

From my server.js

`// BASE SETUP
// ======================================

// CALL THE PACKAGES --------------------
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // get body-parser
var morgan = require('morgan'); // used to see requests
var mongoose = require('mongoose');
var User = require('./app/models/user');
var port = process.env.PORT || 8080; // set the port for our app

// APP CONFIGURATION ---------------------
// use body parser so we can grab information from POST requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// configure our app to handle CORS requests
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});

// log all requests to the console
app.use(morgan('dev'));

// connect to our database (hosted on MLab)
mongoose.connect('mongodb://xxxxxx:xxxxxxx@ds053196.mlab.com:53196/meanmachinebook');

// ROUTES FOR OUR API
// ======================================

// basic route for the home page
app.get('/', function(req, res) {
res.send('Welcome to the home page!');
});

// get an instance of the express router
var apiRouter = express.Router();

// middleware to use for all requests
apiRouter.use(function(req, res, next) {
// do logging
console.log('Somebody just came to our app!');

next(); // make sure we go to the next routes and don't stop here

});

// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

// on routes that end in /users
// ----------------------------------------------------
apiRouter.route('/users')

// create a user (accessed at POST http://localhost:8080/users)
.post(function(req, res) {

    var user = new User();      // create a new instance of the User model
    user.name = req.body.name;  // set the users name (comes from the request)
    user.username = req.body.username;  // set the users username (comes from the request)
    user.password = req.body.password;  // set the users password (comes from the request)

    user.save(function(err) {
        if (err) {
            // duplicate entry
            if (err.code == 11000) 
                return res.json({ success: false, message: 'A user with that username already exists. '});
            else 
                return res.send(err);
        }

        // return a message
        res.json({ message: 'User created!' });
    });

})

// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
    User.find(function(err, users) {
        if (err) return res.send(err);

        // return the users
        res.json(users);
    });
});

// on routes that end in /users/:user_id
// ----------------------------------------------------
apiRouter.route('/users/:user_id')

// get the user with that id
.get(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {
        if (err) return res.send(err);

        // return that user
        res.json(user);
    });
})

// update the user with this id
.put(function(req, res) {
    User.findById(req.params.user_id, function(err, user) {

        if (err) return res.send(err);

        // set the new user information if it exists in the request
        if (req.body.name) user.name = req.body.name;
        if (req.body.username) user.username = req.body.username;
        if (req.body.password) user.password = req.body.password;

        // save the user
        user.save(function(err) {
            if (err) return res.send(err);

            // return a message
            res.json({ message: 'User updated!' });
        });

    });
})

// delete the user with this id
.delete(function(req, res) {
    User.remove({
        _id: req.params.user_id
    }, function(err, user) {
        if (err) return res.send(err);

        res.json({ message: 'Successfully deleted' });
    });
});

// REGISTER OUR ROUTES -------------------------------
app.use('/api', apiRouter);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);`

@peweet
Copy link

peweet commented Nov 18, 2016

Having this exact issue did you ever manage to fix it?

@sahibjotsaggu
Copy link

@mikevarela @peweet Do you guys get any error messages? If so, what are they?

@fe98
Copy link

fe98 commented Aug 20, 2017

Here's the error I'm getting. Guessing this is what they're getting as well...

API Requested
(node:535) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
{ ValidationError: User validation failed: password: Path `password` is required., username: Path `username` is required.
    at ValidationError.inspect (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/error/validation.js:57:23)
    at formatValue (util.js:362:36)
    at inspect (util.js:226:10)
    at format (util.js:98:24)
    at Console.log (console.js:113:24)
    at /mnt/c/Web/mean-machine/server.js:54:19
    at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/model.js:3822:16
    at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/services/model/applyHooks.js:167:17
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  errors:
   { password:
      { ValidatorError: Path `password` is required.
          at ValidatorError (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/error/validator.js:25:11)
          at validate (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:758:13)
          at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:805:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:765:19)
          at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/document.js:1481:9
          at _combinedTickCallback (internal/process/next_tick.js:131:7)
          at process._tickCallback (internal/process/next_tick.js:180:9)
        message: 'Path `password` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'password',
        value: undefined,
        reason: undefined,
        '$isValidatorError': true },
     username:
      { ValidatorError: Path `username` is required.
          at ValidatorError (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/error/validator.js:25:11)
          at validate (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:758:13)
          at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:805:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (/mnt/c/Web/mean-machine/node_modules/mongoose/lib/schematype.js:765:19)
          at /mnt/c/Web/mean-machine/node_modules/mongoose/lib/document.js:1481:9
          at _combinedTickCallback (internal/process/next_tick.js:131:7)
          at process._tickCallback (internal/process/next_tick.js:180:9)
        message: 'Path `username` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'username',
        value: undefined,
        reason: undefined,
        '$isValidatorError': true } },
  _message: 'User validation failed',
  name: 'ValidationError' }
POST /api/users?name=test&username=testusername&password=testpassword 200 78.294 ms - 646

@peweet
Copy link

peweet commented Aug 29, 2017

I forget if I managed to fix but this is what I think I did. If you read the error carefully it tells you exactly whats wrong.
'username' & 'password' values are needed.
The code is executing perfectly but fails as actual values are needed.

So quite simply the validation has failed because the computer is too stupid to figure out what to do when it has nothing to work with! :-)

We need to pass in a generic password and user to fill the undefined value. Or write a usecase to handle the null value.

ie a bit of psuedo

IF empty PRINT 'Sorry buddy you have to type something for me to work ENDIF

So find a way to pass user and password values through the command line to see it works at runtime. If that doesn't work manually try put in values directly into the Javascript.

var user = new User(); // create a new instance of the User model user.name = req.body.'Elvis Presley'; // set the users name (comes from the request) user.username = req.body.'ElvisPresley123'; // set the users username (comes from the request) user.password = req.body.'VivaLasVegas'; // set the users password (comes from the request)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants