arrays - Mongoose 不会更新我在数据库中的数组
问题描述
我正在尝试用猫鼬更新我的收藏。
这是我的架构:
var FamilySchema = mongoose.Schema({
construction: {
type: Array,
default: [
["foundry", 0],
["farm", 0],
["sawmill", 0]
]
}
});
这是我的代码:
app.put('/construction/updateConstruction/:id', (req, res) => {
let id = req.params.id;
Family.findById(id, (err, familiaDB) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
}
if (!familiaDB) {
return res.status(400).json({
ok: false,
err
});
}
// I want to update the value of the posicion 0 in the array.
familiaDB.construction[0][1] = 1;
familiaDB.save();
console.log(familiaDB);
});
});
发出请求后在 console.log 中产生:
Escuchando puerto: 3000
Base de datos ONLINE
{ state: true,
construction:
[ [ 'foundry', 1 ],
[ 'farm', 0 ],
[ 'sawmill', 0 ],
_id: 5bb8d69c604625211c572ada,
__v: 0 }
在 console.log 中一切都很好并且更新了,但在我的数据库中它没有更新。我在 robomongo 中检查过很多次,但从未更新过。
解决方案
最快的方法是使用findOneAndUpdate:
Family.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId("YOURID") },
{ $set: { 'construction.0.1': 'YourValue' }}
)
这将在一个声明中完成。
现在,您可以使用$elemMatch并通过以下方式更新正确的,而不是按索引执行此操作:
Family.findOneAndUpdate(
{_id: ObjectId("YOURID"), 'cons': { $elemMatch: { '0': 'foundry' }}},
{ $set: { 'cons.$.1': 'YourValue' } }
)
推荐阅读
- r - 为唯一 ID 创建所有可能的值组合
- docker - Docker Swarm 中的容器和节点 IP 地址
- node.js - 如何在 Express js 中模拟单元测试的 IP 地址
- python - Word Mover Distance 和 Bert-Embedding 的文档相似度
- java - 在 POI Apache Excel .xls 文档中看不到样式更改
- python - Python 编码技术:使用另一种方法作为接口进行系统调用的类方法
- ios - 自定义 UIView 性能
- docker - Dockerfile 的“/app”工作目录是什么?
- python - 我可以将 macaddr8 列检索为数字吗?
- rest - 查看 chrome 开发人员选项卡上的 api 调用信息