1

Let's say I want to update "numberOfUpVotes" where the title is "Een centrale plek voor alle ideeen". I want the new value of "numberOfUpVotes" to be stored in the database. How do I do that?

Right now my code doesn't give an error, but it also doesn't work. This is what I've tried:

 Board.findOneAndUpdate(
        {"ideas.numberOfUpVotes": 23},
        {$set: {"numberOfUpVotes": 2}}, // $set
        {new: true},
        function (err, doc) {
            if (err) return res.send(500, {error: err});
            console.log("hallo");
        });

This is my data:

{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
    {
    _id: ida1,
    userId: id1,
    title: 'Een centrale plek voor alle ideeen',
    text: 'Een plek waar alle ideeen getoond worden op een scherm ofzo. Waar mensen dan op kunnnen stemmen via hun telefoon',
    date: new Date('2019-04-12'),
    numberOfUpVotes: 23,
    },
    {
    _id: ida2,
    userId: id1,
    title: 'Een uber voor kerstbomen',
    text: 'Bestaat zoiets al?',
    date: new Date('2019-04-11'),
    numberOfUpVotes: 1,
    }
],
QRcode: 'Dit is een QRcode'
}

2 Answers 2

1

You can do this without mongoose, something like.

const board = {
  collectionName: "Board",
  boardName: "IdeaBoard Schiphol",
  ideas: [
      {
      _id: 'ida1 (demo)',
      userId: 'id1 (demo)',
      title: 'Een centrale plek voor alle ideeen',
      text: 'Verkort voor demonstratie',
      date: new Date('2019-04-12'),
      numberOfUpVotes: 23,
      },
      {
      _id: 'ida2 (demo)',
      userId: 'id1 (demo)',
      title: 'Een uber voor kerstbomen',
      text: 'Bestaat zoiets al?',
      date: new Date('2019-04-11'),
      numberOfUpVotes: 1,
      }
  ],
  QRcode: 'Dit is een QRcode'
};

// find the filtered record and update its value
// the found record is a reference, so the value 
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;

// QED
console.log(JSON.stringify(board, null, " "));

Sign up to request clarification or add additional context in comments.

2 Comments

This works only for the object that is returned. I would like to edit the database object as well.
Ah, ok. I'm not well versed in mongoose, but isn't it possible to use a filter function (like in the answer) as first argument? Or maybe Board.findOneAndUpdate([{"ideas.numberOfUpVotes": 23}], ...)?
0

This is my final answer:

Board.update(
    {"ideas._id": mongoose.Types.ObjectId("abc123")},
    {$inc:{"ideas.$.numberOfUpVotes": 1}},
    function (err, doc) {
        if (err) return res.send(500, {error: err});
        console.log("succes! (:");
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.