javascript - 如何用猫鼬更新对象内的数组内的对象?
问题描述
假设我想更新标题为“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'
}
解决方案
你可以在没有猫鼬的情况下做到这一点,比如。
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, " "));
推荐阅读
- google-people-api - 我们可以在 PHP 的 Google People API 中使用多个范围吗
- cmake - CMake“FILES_MATCHING_PATTERN”复制空目录
- knockout.js - hasFocus knoukoutjs 数据绑定如何在 textarea 表单输入上工作
- php - 如何将选择放入数组中?
- jquery - jquery在一定数量的子元素后删除子元素
- kubernetes - 按计划调整实例组的大小
- java - Android中是否有任何用于网络连接检查的注释处理库?
- abap - 哪个具有更好的性能:SELECT...ENDSELECT (1 by 1) 或 SELECT...INTO TABLE / LOOP AT
- memcpy - 如何将 1d qvector 复制到 2d qvector 的特殊列中?
- python - 如何修复 TVL1 光流算法的 opencv 导入