【问题标题】:Cannot set property -hashed_password of null , of addFollower method in nodejs app无法在 nodejs 应用程序中设置 addFollower 方法的 null 属性 -hashed_pa​​ssword
【发布时间】:2021-03-02 17:59:31
【问题描述】:

我的控制器/user.js 文件有以下内容

exports.addFollower= (req,res )=>{
    User.findByIdAndUpdate(req.body.followId, {
        $push:{followers: req.body.user_Id}
    },
             {new : true}
    )
    .populate('following', '_id name')
    .populate('followers', '_id name')
    .exec((err,result)=>{
        if(err){
            return res.status(400).json({
                error:"This is an error "
            })
        }
        result.hashed_password= undefined;
        result.salt = undefined;
        res.json(result)
 
    })
}

我的 routes/user.js 文件有以下内容

const express = require('express');

const {userById ,allUsers, getUser,updateUser,deleteUser ,userPhoto
, addFollowing,
addFollower, removeFollowing, removeFollower
}= require('../controllers/user');
const {requireSignin} = require('../controllers/auth');

const router = express.Router();

router.put('/user/follow', requireSignin, addFollowing,addFollower );
router.put('/user/unfollow', requireSignin, removeFollowing, removeFollower);

用户模型如下

const mongoose = require("mongoose");
let uuidv1 = require('uuidv1');
const crypto = require('crypto');
const {ObjectId} = mongoose.Schema;

const userSchema = new mongoose.Schema({
    name:{
        type:String,
        trim:true,
        required:true
    },
    email:{
        type:String,
        trim:true,
        required:true

    },
    hashed_password:{
        type:String,
        required: true
    },
    salt: String,
    created:{
        type:Date,
        default:Date.now
    },
    updated:Date,
    photo:{
        data:Buffer,
        contentType:String
    },
    about:{
        type:String,
        trim:true
    },
    following:[{type:ObjectId , ref:"User"}],
    followers:[{type:ObjectId, ref:"User"}]

});



//virtual field
userSchema.virtual('password')
.set(function(password){
    //create a temporary variable called _password
    this._password =password
    //generate a timestamp 
    this.salt = uuidv1();   
    //encrypt password
    this.hashed_password= this.encryptPassword(password);   
})
.get(function(){
    return this._password
})

//methods
userSchema.methods = {

   authenticate:function(plainText){

     return this.encryptPassword(plainText) === this.hashed_password

   },

    encryptPassword:function (password){
        if(!password)   
        return "user SCHEMA error";
        
        try{
            return crypto.createHmac('sha1', this.salt)
            .update(password)
            .digest('hex');
             
        }
        catch(err) {

            return "userSchema error 2  ";


        }
    }
}


module.exports= mongoose.model("User",userSchema)

但是当我使用有效令牌点击以下 Route /user/follow 时,我收到以下错误

TypeError:无法将属性“hashed_pa​​ssword”设置为 null 在 rfs\nodeapi\controllers\user.js:180:31

第 180 行指本节

exports.addFollower= (req,res )=>{
    User.findByIdAndUpdate(req.body.followId, {
        $push:{followers: req.body.user_Id}
    },
             {new : true}
    )
    .populate('following', '_id name')
    .populate('followers', '_id name')
    .exec((err,result)=>{
        if(err){
            return res.status(400).json({
                error:"This is an error "
            })
        }
        result.hashed_password= undefined;
        result.salt = undefined;
        res.json(result)


    })

}

如何调试?

感谢您的帮助! :)

【问题讨论】:

    标签: node.js


    【解决方案1】:

    简短的回答是,当您看到此错误时,请交叉检查您的获取请求是什么样的,即使大小写差异很小,mongoose 也会出错,在我的情况下发生了以下情况..

    查看获取请求,发现follow_Id写为follow_id,在addFollower方法中

    export const follow = (user_Id, token,follow_Id)=>{
    
    
    
        return   fetch(`${process.env.REACT_APP_API_URL}/user/follow `,{
              method:"PUT",
              headers:{
                  Accept:"application/json",
                  "Content-Type":"application/json",
                  Authorization:`Bearer ${token}`
              },
              body: JSON.stringify({user_Id,follow_Id})
    
            
          })
          .then(response =>{
              return response.json();
          })
          .catch(err=>console.log(err)
       
          )
        
      }
    

    正确添加Follower方法

    exports.addFollower = (req, res) => {
        User.findByIdAndUpdate(req.body.follow_Id, { $push: { followers: req.body.user_Id } }, { new: true })
            .populate('following', '_id name')
            .populate('followers', '_id name')
            .exec((err, result) => {
                console.log("result " , result);
                console.log(" req.params.follow_id " , req.params.follow_Id);
                console.log(" req.body.user_Id " , req.body.user_Id);
                if (err) {
                    return res.status(400).json({
                        error: err
                    });
                }
                result.hashed_password = undefined;
                result.salt = undefined;
                res.json(result);
            });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多