首页 > 解决方案 > 如何用猫鼬更新对象内的数组内的对象?

问题描述

假设我想更新标题为“Een centrale plek voor alle ideeen”的“numberOfUpVotes”。我希望将“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'
}

标签: javascriptexpressmongoose

解决方案


你可以在没有猫鼬的情况下做到这一点,比如。

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


推荐阅读