简体   繁体   中英

Can someone explain this weird behaviour (nodejs + mongoose)?

I'm trying to access a specific object inside an array in my MongoDB using an id sent from the client, but somehow it returns undefined even though the element with that id exists.

The code:

router.put('/odgovor/:slug', async(req, res, next)=>{   
    const date = new Date();
    const month = new Array();
    month[0] = 'Januar';
    month[1] = 'Februar';
    month[2] = 'Mart';
    month[3] = 'April';
    month[4] = 'Maj';
    month[5] = 'Jun';
    month[6] = 'Jul';
    month[7] = 'Avgust';
    month[8] = 'Septembar';
    month[9] = 'Oktobar';
    month[10] = 'Novembar';
    month[11] = 'Decembar';
    await Post.findOne({slug: req.params.slug}, async(err, post)=>{
        if(err) return next();
        if(!post) return next();

        console.log(post.comments[req.body.commentId]);
        console.log(req.body.commentId);
        console.log(post.comments[12]);

        /*const reply = {
            id: post.comments[req.body.commentId].replies.length,
            date: `${date.getDate()} ${month[date.getMonth()]} ${date.getFullYear()} ${date.getHours()}:${date.getMinutes()}`,
            user: req.body.user,
            username: req.body.username,
            comment: req.body.comment
        }
        post.comments[req.body.commentId].replies.push(reply);
        try{
            post = await post.save();
            res.redirect(`/poezija/${req.params.slug}`);
        }catch(e){
            res.render('errors/500', {token: res.locals.token});
        }*/
    });
});

The console:

undefined
12
{
  id: 12,
  date: '9 Decembar 2020 20:48',
  user: 'name',
  username: 'tests',
  comment: 'tests',
  replies: []
}

What's even more strange, the req.body.commentId is 12 and if I do:

console.log(post.comments[req.body.commentId]);

it returns undefined, but if I do:

console.log(post.comments[12]);

it returns the actual object.

Can someone explain, please?

The callback returns a mongoose Document object as a second argument. Calling the toObject method on the result will convert it to a javascript object and it might fix the issue.

You can find more information in the documentation .

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