无法读取猫鼬中未定义的属性“用户名”

时间:2018-07-06 16:13:03

标签: node.js mongoose

我想在user循环内访问for对象,但出现错误。

User.find({resume :{$ne : null}}, (err,user)=>{
if(err) res.send('ther is some problem for updating resumes') ;
if(user){
    for(var i = 0 ; i < user.length ; i++){
        Like.count({for : user[i].username }, (err,count)=>{
            if(err) res.send('there is something wrong with counting likes');
            console.log('inside: ' + user[i].username);

        })
    }
}
})

user.js

var mongoose = require('mongoose') ; 

var schema = mongoose.Schema({
username : {
    type : String,
    require : true
},
password : {
    type : String,
    require : true ,
},
resume : {
    type : String
},
date : {
    type : Date,
    default : Date.now()
}
})

module.exports= mongoose.model("user",schema) ; 

我无法弄清楚哪里出了问题!

1 个答案:

答案 0 :(得分:0)

尝试一下:

User.find({ resume: { $ne: null } }, (err, users) => {
  if (err) res.send('there is some problem for updating resumes');
  //for debugging, temporarily log number of users found...
  console.log(`${users.length} were found with no resume!`);
  if (users.length > 0) {
    users.forEach((user) => {
      Like.count({ for: user.username }, (err, count) => {
        if (err) res.send('there is something wrong with counting likes');
        console.log('inside: ' + user.username);

      })
    });
  }
});

指针

  • 用户是一个数组,您不能使用if (array)来检查数组是否虚假,因为空数组是真实的。因此,请检查长度if (array.length > 0
  • 这不是您的问题,但是使用本机数组方法比您自己的for循环更安全。 users.forEach ...而不是for (var i = 0; ...