TypeError:无法读取null的属性“ userID”

时间:2019-04-06 00:30:24

标签: javascript mongoose userid

错误:

  

TypeError:无法读取null的属性“ userID”

同时列出了我的UserDB.jsprofileController.js,不确定该错误是什么原因。当我从页面过渡到myItems(cart)时,会吐出此错误。

router.get('/myItems', function(req, res, next){
res.locals.signin = req.session.signin;
var UserDB = require('../models/UserDB');
var Users = UserDB.getUser();
console.log(Users);
var LocalUser = Users.find(function (ele) {if (ele.userID === req.session.signin) {return ele;}});
if (SessionOn) {
    var UserProfiles = UserDB.GetUserProfiles();
    var LocalProfile = UserProfiles.find(function (ele) {if (ele.GetUserID() === LocalUser.userID) {return ele};});
}

res.render('myItems', {LocalUser: LocalUser, LocalProfile: LocalProfile, Session: res.locals.signin, SessionOn: SessionOn});
next()
});

-------------------

var mongoose = require('mongoose');
   mongoose.connect('mongodb://localhost:27017/DB');
   var Schema = mongoose.Schema;

    var userDataSchema = new Schema({
    userID: {type: String, required: true},
    password: {type: String, required: true},
    firstName: {type: String, required: true},
    lastName: {type: String, required: true},
    email: {type: String, required: true},
    city: {type: String, required: true},
    state: {type: String, required: true},
    zipCode: {type: String, required: true}

    },{collection: 'User'});

    var UserData = mongoose.model('User', userDataSchema);

    function getAllUsers(){
    try{
        return UserData.find({});
    } catch(e){
        console.log(e);
    }
    }

    function getUser(user){
    try{
        return  UserData.findOne({userID: user});

    }catch(e){
        console.log("error " + e);
    }
    }

    module.exports.getUser = getUser;
    module.exports.getAllUsers = getAllUsers;

1 个答案:

答案 0 :(得分:0)

您的猫鼬模型查询函数Users.find()为您提供对象数组 因此,如果您想以以前的方式访问它 尝试这样

Users.findOne({userid:xxx},callback);

或者如果使用它的find()方法,则必须访问数组索引

Users.find({userId:xxx},(users)=>{users[0]==neededId}