arrays - $push 在 MongoDb 中不起作用?

标签 arrays node.js mongodb mongoose

我的模式是这样的:

    var exampleSchema = newSchema({
    profile:{
    experience :[{
              exp : String
    }]
   }
  }); 

这是更新配置文件收集体验的代码:

exampleSchema.statics.experience = function (id,experience, callback){
var update = {
        $push: {
          'profile.experience': experience
        }
      }
      this.findByIdAndUpdate(id,update,function(err) {
        if (err) {
          callback(err);
        } else {
          callback(null);
        }
      })

我遇到了这样的错误 The field 'profile.experience' must be an array but is of type String in document {_id: ObjectId('5653f1d852cf7b4c0bfeb54a')}[object Object]

console.log(experience) 等于

{ exp: 'jlkjlkjlk' }

我的收藏应该是这样的:

experience:[
   {
    exp : "YYYY"
    },
   {
    exp:"xxxx"}
 ]

最佳答案

想象一下,您有这个收藏:

/* 1 */
{
    "_id" : ObjectId("565425e862760dfe14339ba8"),
    "profile" : {
        "experience" : [ 
            {
                "exp" : "Experto"
            }
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("565425f562760dfe14339ba9"),
    "profile" : {
        "experience" : {
            "exp" : "Experto"
        }
    }
}

/* 3 */
{
    "_id" : ObjectId("5654260662760dfe14339baa"),
    "profile" : {
        "experience" : "Experto"
    }
}

如果你尝试(更新文档/* 2 */):

db.profile.update(
   { _id: ObjectId("565425f562760dfe14339ba9") },
   { $push: { "profile.experience" : { exp : "Intermediate" } } }
)

你得到这个错误:

The field 'profile.experience' must be an array but is of type Object in document {_id: ObjectId('565425f562760dfe14339ba9')}

如果你尝试(更新文档/* 3 */):

db.profile.update(
   { _id: ObjectId("5654260662760dfe14339baa") },
   { $push: { "profile.experience" : { exp : "Intermediate" } } }
)

您将获得:

The field 'profile.experience' must be an array but is of type String in document {_id: ObjectId('5654260662760dfe14339baa')}

关于arrays - $push 在 MongoDb 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888195/

相关文章:

javascript - 根据过滤键创建新对象

java - 使用 while() 循环检查 .txt 文件中的元素

node.js - Shopify API如何生成发票、运输标签和运输 list ?

node.js - 无法弄清楚为什么docker compose up没有运行我的React JS App

javascript - 编辑仅存在一些文档的内部数组

node.js - Mongoose Schema 如何在数据库更新时更改 date.now

java - 在java中创建自己的后端有意义吗?

java - 如何用更快的东西替换 SortedSet 或加速它

javascript - 在空行上拆分字符串

javascript - 获取Keycloak中登录用户的角色