Ian
Ian

Reputation: 13842

mongodb not saving entry from node.js

Just trying to learn node/mongo/express, so I'm pretty new. I'm following a book and just trying to get some basics going.

I have the following code in user.js..

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/auth_demo');

var user = mongoose.Schema({
  username: String,
  password: String
})

module.exports = mongoose.model('User', user );

and then server-auth.js


var User = require('./user')
var express = require('express')
var bcryptjs = require('bcryptjs')

var app = express();
app.use(require('body-parser').json());

app.post('/user', function( req, res, next ) {
  var user = new User({ username: req.body.username });
  bcryptjs.hash(req.body.password, 10, function( err, hash ) {
    user.password = hash
    console.log( err, hash, user )

    user.save( function( err, user ) {
      if( err ) { throw next( err ) }
      res.send( 201 )
    })
  })
})

When I run node server-auth.js and I enter the following command..

curl -X POST -d '{"username": "somename", "password" : "pass"}' -H 'Content-Type: application/json' localhost:3000/user

I can see in console log of node, it shows the object fine..it also says 'created' in response to the command


null
$2a$10$NjymL8LT40ze6DauEDlX.OLzZMHB09uohbWuhiA0JNVLX8oTiGS1q
{ password: '$2a$10$NjymL8LT40ze6DauEDlX.OLzZMHB09uohbWuhiA0JNVLX8oTiGS1q',
  username: 'somename',
  _id: 561537693097776367ef4d87 }

So it all 'looks' ok.

However, if I then connect to mongo, 'show dbs' shows the auth_demo collection, and if I do a db.auth_demo.find() it doesn't show anything (I've tried saving just locally in mongo and thats fine)?

Upvotes: 0

Views: 1125

Answers (1)

Valijon
Valijon

Reputation: 13103

Try this once you entered into mongo client:

use auth_demo;
db.users.find();

Upvotes: 1

Related Questions