【发布时间】: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_password”设置为 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