简体   繁体   中英

Mongoose - Push Model - RangeError: Maximum call stack size exceeded

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}`
        })
    }
})

您只需要推送_id,而不推送UserSchema中的整个obj,以等待signedInUser.blogPosts.push(newBlogPost._id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM