gpt4 book ai didi

javascript - 如何使用 Mongoose 更新对象内数组内的对象?

转载 作者:行者123 更新时间:2023-11-30 19:35:20 25 4
gpt4 key购买 nike

假设我想更新标题为“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'
}

最佳答案

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

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

关于javascript - 如何使用 Mongoose 更新对象内数组内的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56001440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com