Reputation: 95
When I run my code, I got an error: RangeError: Maximum call stack size exceeded.
I think the problem lies in the line: await signedInUser.blogPosts.push(newBlogPost) But I do not know how to fix it. Please help me!
Here's my code:
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
}
}
Some code:
Veryfy Json Web Token
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
}}
Here's User Schema and Model
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)
Here's BlogPost Schema and Model
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)
Here's my Router
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}`
})
}
})
Upvotes: 0
Views: 215
Reputation: 224
You need to push just the _id not the whole obj in UserSchema await signedInUser.blogPosts.push(newBlogPost._id)
Upvotes: 1