运行代码时,出现错误: RangeError:超出了最大调用堆栈大小。
我认为问题在于: 等待signedInUser.blogPosts.push(newBlogPost) 但是我不知道如何解决它。请帮帮我!
这是我的代码:
const insertBlogPost = async (title, content, tokenKey) => {
try {
//Check token key
let signedInUser = await verifyJWT(tokenKey)
let newBlogPost = await BlogPost.create({
title, content,
date: Date.now(),
author: signedInUser
})
await newBlogPost.save()
await signedInUser.blogPosts.push(newBlogPost)
await signedInUser.save()
return newBlogPost
} catch(error) {
throw error
}
}
某些代码:
非常Json Web令牌
const verifyJWT = async (tokenKey) => {
try {
let decodedJson = await jsonwebtoken.verify(tokenKey, secretString)
if(Date.now() / 1000 > decodedJson.exp) {
throw "Token timeout, please login again"
}
let foundUser = await User.findById(decodedJson.id)
if (!foundUser) {
throw "Not find user with this token"
}
return foundUser
} catch(error) {
throw error
}}
这里的用户架构和模型
const UserSchema = new Schema({
name: {type: String, default: 'unknown', unique: true},
email: {type: String, match:/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, unique: true},
password: {type: String, required: true},
active: {type: Number, default: 0}, //inactive
blogPosts:[{type:mongoose.Schema.Types.ObjectId,ref:'BlogPost'}]
})
const User = mongoose.model('User', UserSchema)
这里的BlogPost架构和模型
const BlogPostSchema = new Schema({
title: {type: String, default: 'Haha', unique: true},
content: {type: String, default: ''},
date: {type: Date, default: Date.now},
author:{type: mongoose.Schema.Types.ObjectId, ref: "User"}
})
const BlogPost = mongoose.model('BlogPost', BlogPostSchema)
这是我的路由器
router.post('/insertBlogPost', async (req, res) =>{
let {title, content} = req.body
//Client send tokenKey
let tokenKey = req.headers['x-access-token']
try {
let newBlogPost = await insertBlogPost(title, content, tokenKey)
res.json({
result: 'ok',
message: 'Create blogpost successfully',
data: newBlogPost
})
} catch(error) {
res.json({
result: 'failed',
message: `Can not create blogpost: Error : ${error}`
})
}
})
答案 0 :(得分:0)
您只需要在UserSchema中推送_id而不是整个obj 等待signedInUser.blogPosts.push(newBlogPost._id)