javascript - 更新 mongodb 中的空数组字段
问题描述
我正在尝试更新其中包含字段的数组。该数组已保存在数据库中,但其中没有字段。有没有办法更新空数组并在其中添加字段
架构
const UserSchema = new Schema({
User: [{
Name:{
type: String,
},
Email:{
type: String,
},
}]
})
该数组已保存在数据库中,但它像这样为空
保存的数据库
"id": 101,
"User":[],
这是我用来更新数组的代码
User.update({id: 101,},
{
$push:{
user:{
Name: "Kevin",
Email: "Kevin@gmail.com",
},
}
},(err, data)=>{
console.log(data)
})
每次我运行代码时数组都不会更新,有谁知道如何解决这个问题?
解决方案
db.getCollection('test2').update({
"id": 101
},
{
$push: {
User: {
$each: [
{
"name": "gibbs"
}
]
}
}
})
使用 更新数组$each
。并且User
应该是大写,因为字段在 mongo 中区分大小写。
输出:
/* 1 */
{
"_id" : ObjectId("5f08753ce96d8884b6bcc92e"),
"id" : 101,
"User" : [
{
"name" : "gibbs"
}
]
}
推荐阅读
- php - 将 API 代码转换为 PHP CURL 时出现问题
- java - 如何使用java交换非常大文件中的行和列
- c# - 项目中的额外文件 (NPGSQL)
- stanford-nlp - 斯坦福 NLP 核心未在标记化中生成“之前”和“之后”节点
- git - Git 责备失败并显示消息:致命:责备::find_origin (D) 中的内部错误
- python - 如何测试列表中的所有元素
- video-streaming - 流媒体服务器或 http 服务器
- ios - 如何使用位置更改动画将一个图像移动到另一个图像视图
- python - 如何在 Django REST Framework 序列化程序中检索具有反向关系查找的多对多字段?
- java - 用于集成测试的 Java 测试项目