简体   繁体   中英

Updating a field in an object in MongoDB

I have this code:

    const project = await Project.findOne({"code":currentUser.groupcode}); // this works

    const card = await Card.findOne({"id":req.body.id}); // this works 

    card.panel = req.body.newSection;
    card.save(); // this works

    project.cards[`${req.body.id}`].panel = req.body.newSection;
    project.save(); // this does not work

I'm trying to update the panel field in both the cards collection and projects collection.

When I log project.cards[`${req.body.id}`].panel , it is the correct value, so it is the correct routing.

What's wrong here?

Try putting await before your save statements and see if it resolves the issue.

If I have guessed your schemas correctly this is the answer:


const project = await Project.findOne({ code: currentUser.groupcode }).populate("cards");

const card = await Card.findOne({ id: req.body.id }); // this works

card.panel = req.body.newSection;
await card.save(); // this works

const cardIndex = project.cards.findIndex(card => card._id.toString() === req.body.id);

project.cards[cardIndex].panel = req.body.newSection;
await project.save(); // this does not work

Ok

I needed to add

project.markModified(`cards.${req.body.id}.panel`)

before project.save();

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