title: how to insert user id along with his posts while posting (after login) in reactjs mongodb
body: <p>i created user login with fetching all posted books in reactjs and mongodb (MERN), but i want to insert user id with his every post in reactjs mongodb, then only he can see his posts in his own admin panel. below are the code perticulars.
  i tried a lot but i got negative, please solve this issue anybody....
  thank in advance...</p>
  
  <p>this is my ./app.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var bodyParser = require('body-parser');
  
  var book = require('./routes/book');
  var auth = require('./routes/auth');
  var app = express();
  
  var mongoose = require('mongoose');
  mongoose.Promise = require('bluebird');
  mongoose.connect('mongodb://localhost/admin_c', { promiseLibrary: require('bluebird') })
  //.connect('mongodb://localhost/mern-crud', { useMongoClient: true, promiseLibrary: require('bluebird') })
    .then(() =&gt;  console.log('connection succesful and port runing on 1004'))
    .catch((err) =&gt; console.error(err));
  
  
  const connectHistoryApiFallback = require('connect-history-api-fallback');
  
  
  
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({'extended':'false'}));
  
  app.use(connectHistoryApiFallback({
  verbose: false
   })); 
  app.use(express.static(path.join(__dirname, 'build')));
  
  app.use('/api/book', book);
  app.use('/api/auth', auth);
  
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  });
  
  // error handler
  app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
  
    // render the error page
    res.status(err.status || 500);
    res.render('error');
  });
  
  module.exports = app;</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./src/index.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
  import ReactDOM from 'react-dom';
  import { BrowserRouter as Router, Route } from 'react-router-dom';
  //import '../../node_modules/bootstrap/dist/css/bootstrap.css';
  import './index.css';
  import App from './App';
  import registerServiceWorker from './registerServiceWorker';
  import Login from './components/Login';
  import Register from './components/Register';
  import Edit from './components/Edit';
  import Create from './components/Create';
  import Show from './components/Show';
  ReactDOM.render(
    &lt;Router&gt;
        &lt;div&gt;
          &lt;Route exact path='/' component={App} /&gt;
          &lt;Route path='/Create' component={Create} /&gt;
          &lt;Route path='/login' component={Login} /&gt;
          &lt;Route path='/register' component={Register} /&gt;
          &lt;Route path='/Show/:id' component={Show} /&gt;
        &lt;/div&gt;
    &lt;/Router&gt;,
    document.getElementById('root')
  );
  registerServiceWorker();</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./src/components/Login.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
  import ReactDOM from 'react-dom';
  import axios from 'axios';
  import { Link } from 'react-router-dom';
  import './Login.css';
  
  class Login extends Component {
  
    constructor() {
      super();
      this.state = {
        username: '',
        password: '',
        message: ''
      };
    }
    onChange = (e) =&gt; {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
    }
  
    onSubmit = (e) =&gt; {
      e.preventDefault();
  
      const { username, password } = this.state;
  
      axios.post('/api/auth/login', { username, password })
        .then((result) =&gt; {
          localStorage.setItem('jwtToken', result.data.token);
          this.setState({ message: '' });
          this.props.history.push('/')
        })
        .catch((error) =&gt; {
          if(error.response.status === 401) {
            this.setState({ message: 'Login failed. Username or password not match' });
          }
        });
    }
  
    render() {
      const { username, password, message } = this.state;
      return (
        &lt;div class="container"&gt;
          &lt;form class="form-signin" onSubmit={this.onSubmit}&gt;
            {message !== '' &amp;&amp;
              &lt;div class="alert alert-warning alert-dismissible" role="alert"&gt;
                { message }
              &lt;/div&gt;
            }
            &lt;h2 class="form-signin-heading"&gt;Please sign in&lt;/h2&gt;
            &lt;label for="inputEmail" class="sr-only"&gt;Email address&lt;/label&gt;
            &lt;input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/&gt;
            &lt;label for="inputPassword" class="sr-only"&gt;Password&lt;/label&gt;
            &lt;input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/&gt;
            &lt;button class="btn btn-lg btn-primary btn-block" type="submit"&gt;Login&lt;/button&gt;
            &lt;p&gt;
              Not a member? &lt;Link to="/register"&gt;&lt;span class="glyphicon glyphicon-plus-sign" aria-hidden="true"&gt;&lt;/span&gt; Register here&lt;/Link&gt;
            &lt;/p&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default Login;</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./routes/auth.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var mongoose = require('mongoose');
  var passport = require('passport');
  var settings = require('../config/settings');
  require('../config/passport')(passport);
  var express = require('express');
  var jwt = require('jsonwebtoken');
  var router = express.Router();
  var User = require("../models/user");
  
  router.post('/register', function(req, res) {
    if (!req.body.username || !req.body.password) {
      res.json({success: false, msg: 'Please pass username and password.'});
    } else {
      var newUser = new User({
        username: req.body.username,
        password: req.body.password
      });
      // save the user
      newUser.save(function(err) {
        if (err) {
          return res.json({success: false, msg: 'Username already exists.'});
        }
        res.json({success: true, msg: 'Successful created new user.'});
      });
    }
  });
  
  router.post('/login', function(req, res) {
    User.findOne({
      username: req.body.username
    }, function(err, user) {
      if (err) throw err;
  
      if (!user) {
        res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
      } else {
        // check if password matches
        user.comparePassword(req.body.password, function (err, isMatch) {
          if (isMatch &amp;&amp; !err) {
            // if user is found and password is right create a token
            var token = jwt.sign(user.toJSON(), settings.secret);
            // return the information including token as JSON
            res.json({success: true, token: 'JWT ' + token});
          } else {
            res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
        });
      }
    });
  });
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./src/Components/Create.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
  import ReactDOM from 'react-dom';
  import axios from 'axios';
  import { Link } from 'react-router-dom';
  
  class Create extends Component {
  
    constructor(props) {
      super(props);
      this.state = {
        isbn: '',
        title: '',
        author: '',
        description: '',
        published_year: '',
        publisher: '',
        newdescription: '',
      };
    }
    
    onChange = (e) =&gt; {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
    }
  
    onSubmit = (e) =&gt; {
      e.preventDefault();
  
      const { isbn, title, author, description, published_year, publisher, newdescription } = this.state;
  
      axios.post('/api/book', { isbn, title, author, description, published_year, publisher, newdescription })
        .then((result) =&gt; {
          this.props.history.push("/")
        });
    }
  
    render() {
      const { auth } = this.props;
  
        var pageTitle = `Welcome, { auth.username }`;
      const { isbn, title, author, description, published_year, publisher, newdescription } = this.state;
      return (
        &lt;div class="container"&gt;
          &lt;div class="panel panel-default"&gt;
            &lt;div class="panel-heading"&gt;
              &lt;h3 class="panel-title"&gt;
                ADD BOOK
              &lt;/h3&gt;
            &lt;/div&gt;
            &lt;div class="panel-body"&gt;
              &lt;h4&gt;&lt;Link to="/"&gt;&lt;span class="glyphicon glyphicon-th-list" aria-hidden="true"&gt;&lt;/span&gt; Book List&lt;/Link&gt;&lt;/h4&gt;
              &lt;form onSubmit={this.onSubmit} method="POST"&gt;
                &lt;div class="form-group"&gt;
                   &lt;h1&gt;testtt{ this.state.username }&lt;/h1&gt;
                  &lt;label for="isbn"&gt;ISBN:&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" /&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="title"&gt;Title:&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" /&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="author"&gt;Author:&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" /&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="description"&gt;Description:&lt;/label&gt;
                  &lt;textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3"&gt;{description}&lt;/textArea&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="published_date"&gt;Published Date:&lt;/label&gt;
                  &lt;input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" /&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="publisher"&gt;Publisher:&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" /&gt;
                &lt;/div&gt;
                &lt;div class="form-group"&gt;
                  &lt;label for="publisher"&gt;Newdescription:&lt;/label&gt;
                  &lt;input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" /&gt;
                &lt;/div&gt;
                &lt;input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" /&gt;
              &lt;/form&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default Create;</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./routes/book.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
  var router = express.Router();
  var mongoose = require('mongoose');
  var Book = require('../models/Book.js');
  var passport = require('passport');
  require('../config/passport')(passport);
  
  /* GET ALL BOOKS */
  router.get('/', passport.authenticate('jwt', { session: false}), function(req, res) {
    var token = getToken(req.headers);
    if (token) {
      Book.find(function (err, books) {
        if (err) return next(err);
        res.json(books);
      });
    } else {
      return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }
  });
  
  /* GET SINGLE BOOK BY ID */
  router.get('/:id', function(req, res, next) {
    Book.findById(req.params.id, function (err, post) {
      if (err) return next(err);
      res.json(post);
    });
  });
  
  /* SAVE BOOK */
  router.post('/', passport.authenticate('jwt', { session: false}), function(req, res) {
    var token = getToken(req.headers);
    if (token) {
      Book.create(req.body, function (err, post) {
        if (err) return next(err);
        res.json(post);
      });
    } else {
      return res.status(403).send({success: false, msg: 'Unauthorized.'});
    }
  });
  
  getToken = function (headers) {
    if (headers &amp;&amp; headers.authorization) {
      var parted = headers.authorization.split(' ');
      if (parted.length === 2) {
        return parted[1];
      } else {
        return null;
      }
    } else {
      return null;
    }
  };
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my ./models/Book.js</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var mongoose = require('mongoose');
  var BookSchema = new mongoose.Schema({
    isbn: String,
    title: String,
    author: String,
    description: String,
    published_date: { type: Date },
    publisher: String,
    postedBy: HERE I NEED TO INCLUDE USER_ID,
    updated_date: { type: Date, default: Date.now },
  });
  
  module.exports = mongoose.model('Book', BookSchema);</code></pre>
  </div>
  </div>
  </p>
  
  <p>This is my package.json</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>{
    "name": "my_app",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "axios": "^0.18.0",
      "bcrypt-nodejs": "0.0.3",
      "bluebird": "^3.5.2",
      "body-parser": "^1.18.3",
      "connect-mongo": "^2.0.1",
      "cookie-parser": "^1.4.3",
      "express": "^4.16.4",
      "express-session": "^1.15.6",
      "jsonwebtoken": "^8.3.0",
      "mongoose": "^5.3.6",
      "morgan": "^1.9.1",
      "passport": "^0.4.0",
      "passport-jwt": "^4.0.0",
      "react": "^16.6.0",
      "react-dom": "^16.6.0",
      "react-router-dom": "^4.3.1",
      "react-scripts": "2.0.5",
      "save": "^2.3.2",
      "serve-favicon": "^2.5.0"
    },
    "scripts": {
      "start": "node ./bin/www",
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    },
    "eslintConfig": {
      "extends": "react-app"
    },
    "browserslist": [
      "&gt;0.2%",
      "not dead",
      "not ie &lt;= 11",
      "not op_mini all"
    ]
  }</code></pre>
  </div>
  </div>
  </p>