使用数组更新MongoDB中的(Javascript)集合列

时间:2019-03-19 16:34:52

标签: javascript arrays ajax mongodb

尝试使用数组作为值更新mongoDB集合时,更新会以静默方式失败。

这不起作用:

var arr = ["test","test1","test2"];
$.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , {
      type: "PUT",
      contentType: "application/json",
      data: JSON.stringify({
        mykey: arr
      }),
      success: function() {
        // Do something
      }, 
      error: function(xhr) {
        console.log(xhr.responseText);
      }
    });

这样做:

$.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , {
      type: "PUT",
      contentType: "application/json",
      data: JSON.stringify({
        mykey: "test"
      }),
      success: function() {
        // Do something
      }, 
      error: function(xhr) {
        console.log(xhr.responseText);
      }
    });

1 个答案:

答案 0 :(得分:0)

事实证明,在ajax数据中将数组进行字符串化之前,我需要对数组进行字符串化:

var arr = ["test","test1","test2"];
arr = JSON.stringify(arr);
$.ajax('http://mordor.fmr.com:8030/techtest?id=80a2c727de877ac9' , {
      type: "PUT",
      contentType: "application/json",
      data: JSON.stringify({
        assignedTechs: arr
      }),
      success: function() {
        // Do something
      }, 
      error: function(xhr) {
        console.log(xhr.responseText);
      }
    });