A
A
Alexey Yakovlev2020-12-23 20:28:20
MongoDB
Alexey Yakovlev, 2020-12-23 20:28:20

Object not being added to array?

I add to the array:

router.post('/add/post/:id', async(req, res) => {
    try {
        const {text, img} = await req.body;
        const user = await User.findById(req.params.id);

        await User.updateOne({
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            password: user.password,
            background: user.background,
            photo: user.photo,
            followers: user.followers,
            posts: []
        },
        {$push: {'posts': {$each: [text, img]}}});

        res.redirect('/profile/'+user._id);
    } catch (e) {
        console.log('error ' + e);
    }
})


But it is added to postsonly the elements of the array, not objects, they are also added only once, but you need at least as many.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yakovlev, 2020-12-23
@aleshaykovlev

router.post('/add/post/:id', async(req, res) => {
    try {
        const {text, img} = await req.body;
        const user = await User.findById(req.params.id);

        await User.updateOne({
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            password: user.password,
            background: user.background,
            photo: user.photo,
            followers: user.followers
        },
        {$push: {posts: {$each: [{text, img}]}}});

        res.redirect('/profile/'+user._id);
    } catch (e) {
        console.log('error ' + e);
    }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question