how to insert user id along with his posts while posting (after login) in reactjs mongodb











up vote
0
down vote

favorite












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...



this is my ./app.js






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(() => console.log('connection succesful and port runing on 1004'))
.catch((err) => 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;





This is my ./src/index.js






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(
<Router>
<div>
<Route exact path='/' component={App} />
<Route path='/Create' component={Create} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<Route path='/Show/:id' component={Show} />
</div>
</Router>,
document.getElementById('root')
);
registerServiceWorker();





This is my ./src/components/Login.js






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) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}

onSubmit = (e) => {
e.preventDefault();

const { username, password } = this.state;

axios.post('/api/auth/login', { username, password })
.then((result) => {
localStorage.setItem('jwtToken', result.data.token);
this.setState({ message: '' });
this.props.history.push('/')
})
.catch((error) => {
if(error.response.status === 401) {
this.setState({ message: 'Login failed. Username or password not match' });
}
});
}

render() {
const { username, password, message } = this.state;
return (
<div class="container">
<form class="form-signin" onSubmit={this.onSubmit}>
{message !== '' &&
<div class="alert alert-warning alert-dismissible" role="alert">
{ message }
</div>
}
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
<p>
Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
</p>
</form>
</div>
);
}
}

export default Login;





This is my ./routes/auth.js






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 && !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;





This is my ./src/Components/Create.js






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) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}

onSubmit = (e) => {
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) => {
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 (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
ADD BOOK
</h3>
</div>
<div class="panel-body">
<h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
<form onSubmit={this.onSubmit} method="POST">
<div class="form-group">
<h1>testtt{ this.state.username }</h1>
<label for="isbn">ISBN:</label>
<input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
</div>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
</div>
<div class="form-group">
<label for="author">Author:</label>
<input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
</div>
<div class="form-group">
<label for="description">Description:</label>
<textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
</div>
<div class="form-group">
<label for="published_date">Published Date:</label>
<input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
</div>
<div class="form-group">
<label for="publisher">Publisher:</label>
<input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
</div>
<div class="form-group">
<label for="publisher">Newdescription:</label>
<input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
</div>
<input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
</form>
</div>
</div>
</div>
);
}
}

export default Create;





This is my ./routes/book.js






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 && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};

module.exports = router;





This is my ./models/Book.js






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





This is my package.json






{
"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": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}












share|improve this question




























    up vote
    0
    down vote

    favorite












    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...



    this is my ./app.js






    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(() => console.log('connection succesful and port runing on 1004'))
    .catch((err) => 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;





    This is my ./src/index.js






    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(
    <Router>
    <div>
    <Route exact path='/' component={App} />
    <Route path='/Create' component={Create} />
    <Route path='/login' component={Login} />
    <Route path='/register' component={Register} />
    <Route path='/Show/:id' component={Show} />
    </div>
    </Router>,
    document.getElementById('root')
    );
    registerServiceWorker();





    This is my ./src/components/Login.js






    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) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
    }

    onSubmit = (e) => {
    e.preventDefault();

    const { username, password } = this.state;

    axios.post('/api/auth/login', { username, password })
    .then((result) => {
    localStorage.setItem('jwtToken', result.data.token);
    this.setState({ message: '' });
    this.props.history.push('/')
    })
    .catch((error) => {
    if(error.response.status === 401) {
    this.setState({ message: 'Login failed. Username or password not match' });
    }
    });
    }

    render() {
    const { username, password, message } = this.state;
    return (
    <div class="container">
    <form class="form-signin" onSubmit={this.onSubmit}>
    {message !== '' &&
    <div class="alert alert-warning alert-dismissible" role="alert">
    { message }
    </div>
    }
    <h2 class="form-signin-heading">Please sign in</h2>
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
    <p>
    Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
    </p>
    </form>
    </div>
    );
    }
    }

    export default Login;





    This is my ./routes/auth.js






    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 && !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;





    This is my ./src/Components/Create.js






    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) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
    }

    onSubmit = (e) => {
    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) => {
    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 (
    <div class="container">
    <div class="panel panel-default">
    <div class="panel-heading">
    <h3 class="panel-title">
    ADD BOOK
    </h3>
    </div>
    <div class="panel-body">
    <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
    <form onSubmit={this.onSubmit} method="POST">
    <div class="form-group">
    <h1>testtt{ this.state.username }</h1>
    <label for="isbn">ISBN:</label>
    <input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
    </div>
    <div class="form-group">
    <label for="title">Title:</label>
    <input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
    </div>
    <div class="form-group">
    <label for="author">Author:</label>
    <input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
    </div>
    <div class="form-group">
    <label for="description">Description:</label>
    <textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
    </div>
    <div class="form-group">
    <label for="published_date">Published Date:</label>
    <input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
    </div>
    <div class="form-group">
    <label for="publisher">Publisher:</label>
    <input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
    </div>
    <div class="form-group">
    <label for="publisher">Newdescription:</label>
    <input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
    </div>
    <input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
    </form>
    </div>
    </div>
    </div>
    );
    }
    }

    export default Create;





    This is my ./routes/book.js






    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 && headers.authorization) {
    var parted = headers.authorization.split(' ');
    if (parted.length === 2) {
    return parted[1];
    } else {
    return null;
    }
    } else {
    return null;
    }
    };

    module.exports = router;





    This is my ./models/Book.js






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





    This is my package.json






    {
    "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": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
    ]
    }












    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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...



      this is my ./app.js






      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(() => console.log('connection succesful and port runing on 1004'))
      .catch((err) => 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;





      This is my ./src/index.js






      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(
      <Router>
      <div>
      <Route exact path='/' component={App} />
      <Route path='/Create' component={Create} />
      <Route path='/login' component={Login} />
      <Route path='/register' component={Register} />
      <Route path='/Show/:id' component={Show} />
      </div>
      </Router>,
      document.getElementById('root')
      );
      registerServiceWorker();





      This is my ./src/components/Login.js






      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      e.preventDefault();

      const { username, password } = this.state;

      axios.post('/api/auth/login', { username, password })
      .then((result) => {
      localStorage.setItem('jwtToken', result.data.token);
      this.setState({ message: '' });
      this.props.history.push('/')
      })
      .catch((error) => {
      if(error.response.status === 401) {
      this.setState({ message: 'Login failed. Username or password not match' });
      }
      });
      }

      render() {
      const { username, password, message } = this.state;
      return (
      <div class="container">
      <form class="form-signin" onSubmit={this.onSubmit}>
      {message !== '' &&
      <div class="alert alert-warning alert-dismissible" role="alert">
      { message }
      </div>
      }
      <h2 class="form-signin-heading">Please sign in</h2>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
      <p>
      Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
      </p>
      </form>
      </div>
      );
      }
      }

      export default Login;





      This is my ./routes/auth.js






      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 && !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;





      This is my ./src/Components/Create.js






      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      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) => {
      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 (
      <div class="container">
      <div class="panel panel-default">
      <div class="panel-heading">
      <h3 class="panel-title">
      ADD BOOK
      </h3>
      </div>
      <div class="panel-body">
      <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
      <form onSubmit={this.onSubmit} method="POST">
      <div class="form-group">
      <h1>testtt{ this.state.username }</h1>
      <label for="isbn">ISBN:</label>
      <input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
      </div>
      <div class="form-group">
      <label for="title">Title:</label>
      <input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
      </div>
      <div class="form-group">
      <label for="author">Author:</label>
      <input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
      </div>
      <div class="form-group">
      <label for="description">Description:</label>
      <textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
      </div>
      <div class="form-group">
      <label for="published_date">Published Date:</label>
      <input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
      </div>
      <div class="form-group">
      <label for="publisher">Publisher:</label>
      <input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
      </div>
      <div class="form-group">
      <label for="publisher">Newdescription:</label>
      <input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
      </div>
      <input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
      </form>
      </div>
      </div>
      </div>
      );
      }
      }

      export default Create;





      This is my ./routes/book.js






      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 && headers.authorization) {
      var parted = headers.authorization.split(' ');
      if (parted.length === 2) {
      return parted[1];
      } else {
      return null;
      }
      } else {
      return null;
      }
      };

      module.exports = router;





      This is my ./models/Book.js






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





      This is my package.json






      {
      "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": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
      ]
      }












      share|improve this question















      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...



      this is my ./app.js






      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(() => console.log('connection succesful and port runing on 1004'))
      .catch((err) => 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;





      This is my ./src/index.js






      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(
      <Router>
      <div>
      <Route exact path='/' component={App} />
      <Route path='/Create' component={Create} />
      <Route path='/login' component={Login} />
      <Route path='/register' component={Register} />
      <Route path='/Show/:id' component={Show} />
      </div>
      </Router>,
      document.getElementById('root')
      );
      registerServiceWorker();





      This is my ./src/components/Login.js






      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      e.preventDefault();

      const { username, password } = this.state;

      axios.post('/api/auth/login', { username, password })
      .then((result) => {
      localStorage.setItem('jwtToken', result.data.token);
      this.setState({ message: '' });
      this.props.history.push('/')
      })
      .catch((error) => {
      if(error.response.status === 401) {
      this.setState({ message: 'Login failed. Username or password not match' });
      }
      });
      }

      render() {
      const { username, password, message } = this.state;
      return (
      <div class="container">
      <form class="form-signin" onSubmit={this.onSubmit}>
      {message !== '' &&
      <div class="alert alert-warning alert-dismissible" role="alert">
      { message }
      </div>
      }
      <h2 class="form-signin-heading">Please sign in</h2>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
      <p>
      Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
      </p>
      </form>
      </div>
      );
      }
      }

      export default Login;





      This is my ./routes/auth.js






      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 && !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;





      This is my ./src/Components/Create.js






      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      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) => {
      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 (
      <div class="container">
      <div class="panel panel-default">
      <div class="panel-heading">
      <h3 class="panel-title">
      ADD BOOK
      </h3>
      </div>
      <div class="panel-body">
      <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
      <form onSubmit={this.onSubmit} method="POST">
      <div class="form-group">
      <h1>testtt{ this.state.username }</h1>
      <label for="isbn">ISBN:</label>
      <input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
      </div>
      <div class="form-group">
      <label for="title">Title:</label>
      <input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
      </div>
      <div class="form-group">
      <label for="author">Author:</label>
      <input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
      </div>
      <div class="form-group">
      <label for="description">Description:</label>
      <textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
      </div>
      <div class="form-group">
      <label for="published_date">Published Date:</label>
      <input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
      </div>
      <div class="form-group">
      <label for="publisher">Publisher:</label>
      <input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
      </div>
      <div class="form-group">
      <label for="publisher">Newdescription:</label>
      <input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
      </div>
      <input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
      </form>
      </div>
      </div>
      </div>
      );
      }
      }

      export default Create;





      This is my ./routes/book.js






      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 && headers.authorization) {
      var parted = headers.authorization.split(' ');
      if (parted.length === 2) {
      return parted[1];
      } else {
      return null;
      }
      } else {
      return null;
      }
      };

      module.exports = router;





      This is my ./models/Book.js






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





      This is my package.json






      {
      "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": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
      ]
      }








      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(() => console.log('connection succesful and port runing on 1004'))
      .catch((err) => 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;





      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(() => console.log('connection succesful and port runing on 1004'))
      .catch((err) => 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;





      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(
      <Router>
      <div>
      <Route exact path='/' component={App} />
      <Route path='/Create' component={Create} />
      <Route path='/login' component={Login} />
      <Route path='/register' component={Register} />
      <Route path='/Show/:id' component={Show} />
      </div>
      </Router>,
      document.getElementById('root')
      );
      registerServiceWorker();





      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(
      <Router>
      <div>
      <Route exact path='/' component={App} />
      <Route path='/Create' component={Create} />
      <Route path='/login' component={Login} />
      <Route path='/register' component={Register} />
      <Route path='/Show/:id' component={Show} />
      </div>
      </Router>,
      document.getElementById('root')
      );
      registerServiceWorker();





      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      e.preventDefault();

      const { username, password } = this.state;

      axios.post('/api/auth/login', { username, password })
      .then((result) => {
      localStorage.setItem('jwtToken', result.data.token);
      this.setState({ message: '' });
      this.props.history.push('/')
      })
      .catch((error) => {
      if(error.response.status === 401) {
      this.setState({ message: 'Login failed. Username or password not match' });
      }
      });
      }

      render() {
      const { username, password, message } = this.state;
      return (
      <div class="container">
      <form class="form-signin" onSubmit={this.onSubmit}>
      {message !== '' &&
      <div class="alert alert-warning alert-dismissible" role="alert">
      { message }
      </div>
      }
      <h2 class="form-signin-heading">Please sign in</h2>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
      <p>
      Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
      </p>
      </form>
      </div>
      );
      }
      }

      export default Login;





      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      e.preventDefault();

      const { username, password } = this.state;

      axios.post('/api/auth/login', { username, password })
      .then((result) => {
      localStorage.setItem('jwtToken', result.data.token);
      this.setState({ message: '' });
      this.props.history.push('/')
      })
      .catch((error) => {
      if(error.response.status === 401) {
      this.setState({ message: 'Login failed. Username or password not match' });
      }
      });
      }

      render() {
      const { username, password, message } = this.state;
      return (
      <div class="container">
      <form class="form-signin" onSubmit={this.onSubmit}>
      {message !== '' &&
      <div class="alert alert-warning alert-dismissible" role="alert">
      { message }
      </div>
      }
      <h2 class="form-signin-heading">Please sign in</h2>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" class="form-control" placeholder="Email address" name="username" value={username} onChange={this.onChange} required/>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" class="form-control" placeholder="Password" name="password" value={password} onChange={this.onChange} required/>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
      <p>
      Not a member? <Link to="/register"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Register here</Link>
      </p>
      </form>
      </div>
      );
      }
      }

      export default Login;





      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 && !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;





      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 && !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;





      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      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) => {
      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 (
      <div class="container">
      <div class="panel panel-default">
      <div class="panel-heading">
      <h3 class="panel-title">
      ADD BOOK
      </h3>
      </div>
      <div class="panel-body">
      <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
      <form onSubmit={this.onSubmit} method="POST">
      <div class="form-group">
      <h1>testtt{ this.state.username }</h1>
      <label for="isbn">ISBN:</label>
      <input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
      </div>
      <div class="form-group">
      <label for="title">Title:</label>
      <input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
      </div>
      <div class="form-group">
      <label for="author">Author:</label>
      <input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
      </div>
      <div class="form-group">
      <label for="description">Description:</label>
      <textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
      </div>
      <div class="form-group">
      <label for="published_date">Published Date:</label>
      <input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
      </div>
      <div class="form-group">
      <label for="publisher">Publisher:</label>
      <input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
      </div>
      <div class="form-group">
      <label for="publisher">Newdescription:</label>
      <input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
      </div>
      <input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
      </form>
      </div>
      </div>
      </div>
      );
      }
      }

      export default Create;





      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) => {
      const state = this.state
      state[e.target.name] = e.target.value;
      this.setState(state);
      }

      onSubmit = (e) => {
      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) => {
      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 (
      <div class="container">
      <div class="panel panel-default">
      <div class="panel-heading">
      <h3 class="panel-title">
      ADD BOOK
      </h3>
      </div>
      <div class="panel-body">
      <h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Book List</Link></h4>
      <form onSubmit={this.onSubmit} method="POST">
      <div class="form-group">
      <h1>testtt{ this.state.username }</h1>
      <label for="isbn">ISBN:</label>
      <input type="text" class="form-control" name="isbn" value={isbn} onChange={this.onChange} placeholder="ISBN" />
      </div>
      <div class="form-group">
      <label for="title">Title:</label>
      <input type="text" class="form-control" name="title" value={title} onChange={this.onChange} placeholder="Title" />
      </div>
      <div class="form-group">
      <label for="author">Author:</label>
      <input type="text" class="form-control" name="author" value={author} onChange={this.onChange} placeholder="Author" />
      </div>
      <div class="form-group">
      <label for="description">Description:</label>
      <textArea class="form-control" name="description" onChange={this.onChange} placeholder="Description" cols="80" rows="3">{description}</textArea>
      </div>
      <div class="form-group">
      <label for="published_date">Published Date:</label>
      <input type="number" class="form-control" name="published_year" value={published_year} onChange={this.onChange} placeholder="Published Year" />
      </div>
      <div class="form-group">
      <label for="publisher">Publisher:</label>
      <input type="text" class="form-control" name="publisher" value={publisher} onChange={this.onChange} placeholder="Publisher" />
      </div>
      <div class="form-group">
      <label for="publisher">Newdescription:</label>
      <input type="text" class="form-control" name="newdescription" value={newdescription} onChange={this.onChange} placeholder="New Description" />
      </div>
      <input type="submit" name="comment_submit" class="btn btn-primary btn-nexgweb btn-block" value="Submit" />
      </form>
      </div>
      </div>
      </div>
      );
      }
      }

      export default Create;





      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 && headers.authorization) {
      var parted = headers.authorization.split(' ');
      if (parted.length === 2) {
      return parted[1];
      } else {
      return null;
      }
      } else {
      return null;
      }
      };

      module.exports = router;





      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 && headers.authorization) {
      var parted = headers.authorization.split(' ');
      if (parted.length === 2) {
      return parted[1];
      } else {
      return null;
      }
      } else {
      return null;
      }
      };

      module.exports = router;





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





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





      {
      "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": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
      ]
      }





      {
      "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": [
      ">0.2%",
      "not dead",
      "not ie <= 11",
      "not op_mini all"
      ]
      }






      reactjs mongodb






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 10:43

























      asked Nov 8 at 10:33









      Ganesh

      35




      35
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          hey you have to ref the user id in book schema like



          var BookSchema = new mongoose.Schema({
          isbn: String,
          title: String,
          author: String,
          description: String,
          published_date: { type: Date },
          publisher: String,
          postedBy:type: {type:Schema.Types.ObjectId, ref:'user'},
          updated_date: { type: Date, default: Date.now },
          });


          like this and insert it into when you posting a book send it through this id through req.body with keyword postedBy your req.body should be like



          isbn: 'any thing',
          title: 'any thing',
          author: 'any thing',
          description: 'any thing',
          published_date: 'any thing',
          publisher: 'any thing',
          postedBy: 'user._id',


          . while retrieving it check it user._id is equal to book id like



            Book.find({postedBy:req.body.userid(or any other format you want like query params)},function (err, books) {
          if (err) return next(err);
          res.json(books);
          });
          } else {
          return res.status(403).send({success: false, msg: 'Unauthorized.'});
          }





          share|improve this answer





















          • thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
            – Ganesh
            Nov 8 at 11:05












          • in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
            – Ganesh
            Nov 8 at 11:09










          • please solve this issue....
            – Ganesh
            Nov 8 at 12:07











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205918%2fhow-to-insert-user-id-along-with-his-posts-while-posting-after-login-in-reactj%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote













          hey you have to ref the user id in book schema like



          var BookSchema = new mongoose.Schema({
          isbn: String,
          title: String,
          author: String,
          description: String,
          published_date: { type: Date },
          publisher: String,
          postedBy:type: {type:Schema.Types.ObjectId, ref:'user'},
          updated_date: { type: Date, default: Date.now },
          });


          like this and insert it into when you posting a book send it through this id through req.body with keyword postedBy your req.body should be like



          isbn: 'any thing',
          title: 'any thing',
          author: 'any thing',
          description: 'any thing',
          published_date: 'any thing',
          publisher: 'any thing',
          postedBy: 'user._id',


          . while retrieving it check it user._id is equal to book id like



            Book.find({postedBy:req.body.userid(or any other format you want like query params)},function (err, books) {
          if (err) return next(err);
          res.json(books);
          });
          } else {
          return res.status(403).send({success: false, msg: 'Unauthorized.'});
          }





          share|improve this answer





















          • thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
            – Ganesh
            Nov 8 at 11:05












          • in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
            – Ganesh
            Nov 8 at 11:09










          • please solve this issue....
            – Ganesh
            Nov 8 at 12:07















          up vote
          0
          down vote













          hey you have to ref the user id in book schema like



          var BookSchema = new mongoose.Schema({
          isbn: String,
          title: String,
          author: String,
          description: String,
          published_date: { type: Date },
          publisher: String,
          postedBy:type: {type:Schema.Types.ObjectId, ref:'user'},
          updated_date: { type: Date, default: Date.now },
          });


          like this and insert it into when you posting a book send it through this id through req.body with keyword postedBy your req.body should be like



          isbn: 'any thing',
          title: 'any thing',
          author: 'any thing',
          description: 'any thing',
          published_date: 'any thing',
          publisher: 'any thing',
          postedBy: 'user._id',


          . while retrieving it check it user._id is equal to book id like



            Book.find({postedBy:req.body.userid(or any other format you want like query params)},function (err, books) {
          if (err) return next(err);
          res.json(books);
          });
          } else {
          return res.status(403).send({success: false, msg: 'Unauthorized.'});
          }





          share|improve this answer





















          • thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
            – Ganesh
            Nov 8 at 11:05












          • in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
            – Ganesh
            Nov 8 at 11:09










          • please solve this issue....
            – Ganesh
            Nov 8 at 12:07













          up vote
          0
          down vote










          up vote
          0
          down vote









          hey you have to ref the user id in book schema like



          var BookSchema = new mongoose.Schema({
          isbn: String,
          title: String,
          author: String,
          description: String,
          published_date: { type: Date },
          publisher: String,
          postedBy:type: {type:Schema.Types.ObjectId, ref:'user'},
          updated_date: { type: Date, default: Date.now },
          });


          like this and insert it into when you posting a book send it through this id through req.body with keyword postedBy your req.body should be like



          isbn: 'any thing',
          title: 'any thing',
          author: 'any thing',
          description: 'any thing',
          published_date: 'any thing',
          publisher: 'any thing',
          postedBy: 'user._id',


          . while retrieving it check it user._id is equal to book id like



            Book.find({postedBy:req.body.userid(or any other format you want like query params)},function (err, books) {
          if (err) return next(err);
          res.json(books);
          });
          } else {
          return res.status(403).send({success: false, msg: 'Unauthorized.'});
          }





          share|improve this answer












          hey you have to ref the user id in book schema like



          var BookSchema = new mongoose.Schema({
          isbn: String,
          title: String,
          author: String,
          description: String,
          published_date: { type: Date },
          publisher: String,
          postedBy:type: {type:Schema.Types.ObjectId, ref:'user'},
          updated_date: { type: Date, default: Date.now },
          });


          like this and insert it into when you posting a book send it through this id through req.body with keyword postedBy your req.body should be like



          isbn: 'any thing',
          title: 'any thing',
          author: 'any thing',
          description: 'any thing',
          published_date: 'any thing',
          publisher: 'any thing',
          postedBy: 'user._id',


          . while retrieving it check it user._id is equal to book id like



            Book.find({postedBy:req.body.userid(or any other format you want like query params)},function (err, books) {
          if (err) return next(err);
          res.json(books);
          });
          } else {
          return res.status(403).send({success: false, msg: 'Unauthorized.'});
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 10:51









          Omega Cube

          23118




          23118












          • thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
            – Ganesh
            Nov 8 at 11:05












          • in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
            – Ganesh
            Nov 8 at 11:09










          • please solve this issue....
            – Ganesh
            Nov 8 at 12:07


















          • thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
            – Ganesh
            Nov 8 at 11:05












          • in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
            – Ganesh
            Nov 8 at 11:09










          • please solve this issue....
            – Ganesh
            Nov 8 at 12:07
















          thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
          – Ganesh
          Nov 8 at 11:05






          thanks for your support, i applied the above lines but it is showing {postedBy:type: {type:Schema.Types.ObjectId, ref:'user'}} syntax error while compiling....
          – Ganesh
          Nov 8 at 11:05














          in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
          – Ganesh
          Nov 8 at 11:09




          in ./models/Book.js i added postedBy:type: {type:Schema.Types.ObjectId, ref:'user' this line and in ./src/Components/Create.js i edited this section as you said isbn: '', title: '', author: '', description: '', published_year: '', publisher: '', newdescription: '', postedBy: 'user._id' but syntax error in ./model/Book.js showinw while compiling....
          – Ganesh
          Nov 8 at 11:09












          please solve this issue....
          – Ganesh
          Nov 8 at 12:07




          please solve this issue....
          – Ganesh
          Nov 8 at 12:07


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205918%2fhow-to-insert-user-id-along-with-his-posts-while-posting-after-login-in-reactj%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Schultheiß

          Verwaltungsgliederung Dänemarks

          Liste der Kulturdenkmale in Wilsdruff