Как обновить объект внутри массива внутри объекта с помощью mongoose? - PullRequest
1 голос
/ 06 мая 2019

Допустим, я хочу обновить "numberOfUpVotes", где заголовок "Een centrale plek voor alle ideeen".Я хочу, чтобы новое значение "numberOfUpVotes" было сохранено в базе данных.Как я могу это сделать?

Прямо сейчас мой код не выдает ошибку, но он также не работает.Вот что я пробовал:

 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");
        });

Это мои данные:

{
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 ]

1 голос
/ 06 мая 2019

Вы можете сделать это без мангуста, что-то вроде.

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, " "));
0 голосов
/ 07 мая 2019

Это мой окончательный ответ:

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! (:");
    })
...