A
A
Alexey Yakovlev2021-02-23 19:35:11
MongoDB
Alexey Yakovlev, 2021-02-23 19:35:11

2 objects are created in the database, why?

I receive data from the client and update the array of user books, adding the text of the book, its title, etc., but one object is created separately with the text and the other without it, what did I do wrong?

router.post('/profile/:id/book', async(req, res) => {
    try {
        // get info from client
        const {name, img, textBook} = req.body;
        
        // search user
        const user = await User.findById(req.params.id);

        // update finded user
        await User.updateOne({
            email: user.email
        }, {
            $push: {
                books: {$each: [{
                    name,
                    img,
                    text: textBook,
                    author: `${user.firstName} ${user.lastName}`,
                    authorID: user._id
                }], $position: 0}
            }
        });

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


60352e9da5485396726526.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gsaw, 2021-02-23
@gsaw

Well, apparently you have two different records, with different names. I think everything is ok with your code, rather the problem is with the data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question