Паспорт JS (Стратегия JWT) Objectid undefinied - PullRequest
0 голосов
/ 04 августа 2020

Я работаю над приложением, которое позволяет людям загружать вещи, которые они не хотят продавать. У меня две коллекции - листинги и пользователи. Для каждого листинга я хочу добавить ObjectID пользователя, чтобы установить sh связь. Однако я получаю сообщение об ошибке, показывающее, что ObjectID не определен.

Схема списки. js

const mongoose = require('mongoose');

const listingSchema = new mongoose.Schema({
        name: { type: String },
        category: { type: String },
        description: { type: String },
        image_url: {type: String},
        quantity: { type: Number },
        price: {type: mongoose.Types.Decimal128 },
        meetup: {type: String},
        condition: {type: String},
        created_date: { type: Date, default: Date.now },
        last_updated_date: { type: Date, default: Date.now },
        userID: [{type: mongoose.Schema.Types.ObjectId, ref: 'users'}]
});

const Listings = mongoose.model('listings', listingSchema);

module.exports = Listings;

пользователь. js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');


const userSchema = new mongoose.Schema({
        username: {
                type: String,
                required: true,
                min: 6,
                max: 15
        },
        password: {
                type: String,
                required: true,
                min: 8,
                max: 15
        },
        email: {
                type: String,
                lowercase: true,
                required: true 
        },
        mobile: {
                type: Number,
                required: true 
        },
        created_date: { type: Date, default: Date.now },
        shoppingcart: [
                {
                        productID: { type: String },
                        quantity: { type: Number }
                }
        ]
});

userSchema.pre('save', function (next) {
        if (!this.isModified('password'))
                return next();
        bcrypt.hash(this.password, 10, (err, passwordHash) => {
                if (err)
                        return next(err);
                this.password = passwordHash;
                next();
        });

});

userSchema.methods.comparePassword = function (password, cb) {
        bcrypt.compare(password, this.password, (err, isMatch) => {
                if (err)
                        return cb(err);
                else {
                        if (!isMatch)
                                return cb(null, isMatch);
                        return cb(null, this)
                }
        })
}


const User = mongoose.model('users', userSchema);

module.exports = User;

пользовательский контроллер. js

const express = require('express');
const router = express.Router();
const User = require('../models/user')
const passport = require('passport');
const passportConfig = require('../passport');
const JWT = require('jsonwebtoken');


const signToken = userID => {
    return JWT.sign({
        iss : "ilovestackoverflow",
        sub: userID 
    }, "ilovestackoverflow", {expiresIn: "1h"})
}

router.get('/', (req, res) => {
    User.find({}, (err, foundUser) => {
        res.json(foundUser);
    });
});


// User register 
router.post('/signup', (req, res) => {
    const {username, password, email, mobile} = req.body
    console.log(req.body)
    User.findOne({username}, (err,user) => {
        if (err){
            res.status(500).json({message: {msgbody: "Error has occured!", msgError: true}})
        } else if (user){
            res.status(500).json({message: {msgbody: "Username is already taken!", msgError: true}})
        } else {
            const newUser = new User({username, password,email, mobile});
            console.log(newUser)
            newUser.save(err=> {
                if (err){
                    res.status(500).json({message: {msgbody: "Username is already taken!", msgError: true}})
                } else{
                    res.status(201).json({message: {msgbody: "Account successfully create", msgError: false}})
                }
            })
        }
    })  
})

router.post('/login', passport.authenticate('local', {session: false}), (req, res) => {
    if(req.isAuthenticated()){
        const {_id, username} = req.user;
        const token = signToken(_id);
        res.cookie('access_token', token, {httpOnly: true, sameSite: true});
        res.status(200).json({isAuthenticated: true, user: {username}});
    }
})

router.get('/logout', passport.authenticate('jwt', {session: false}), (req, res) => {
    res.clearCookie('access_token');
    res.json({user:{username: ""}, success: true});
})

router.get('/authenticated', passport.authenticate('jwt', {session: false}), (req, res) => {
        const {username,role} = req.user;
        res.status(200).json({isAuthenticated: true, user: {username,role}});
    })
    

module.exports = router;

список контроллеров. js

const express = require('express');
const router = express.Router();
const Listings = require('../models/listings.js')
const User = require('../models/user');

//create listing route 
router.post('/create', async (req, res) => {

    const listing = new Listings({
        name: req.body.name,
        category: req.body.category,
        description: req.body.description,
        image_url: req.body.image_url,
        quantity: req.body.quantity,
        price: req.body.price,
        meetup: req.body.meetup,
        condition: req.body.condition,
        userID: req.user._id
      })
      await listing.save()
      res.send(listing)
});

//find by id route 
router.get('/:listingID', (req, res) => {
    Listings.findById(req.params.listingID, (err, foundListings) => {
        if (err) {
            res.status(500).json({ message: { msgbody: err, msgError: true } })
        } else {
            res.json(foundListings);
        }
    });
});

//create Index route 
router.get('/', (req, res) => {
    Listings.find({}, (err, foundListings) => {
        res.json(foundListings);
    });
});

//create Delete route 
router.delete('/:listingID', (req, res) => {
    Listings.findByIdAndRemove(req.params.listingID, (err, deletedListing) => {
        res.json(deletedListing);
    });
});

//create Update route
router.put('/:listingID', (req, res) => {
    Listings.findByIdAndUpdate(req.params.listingID, req.body, { new: true }, (err, updatedListing) => {
        res.json(updatedListing);
    });
});

module.exports = router;
...