简体   繁体   English

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

[英]Update (Javascript) collection column in MongoDB with array

When attempting to update a mongoDB collection with an array as the value, the update fails silently. 尝试使用数组作为值更新mongoDB集合时,更新将以静默方式失败。

This does not work: 这不起作用:

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);
      }
    });

This does: 这样做:

$.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);
      }
    });

It turns out I need to stringify the array before stringifying it within the ajax data: 事实证明我需要在将数组在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);
      }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM