【问题标题】:What JSON should i put in REST Client to test the given Schema我应该在 REST 客户端中放入什么 JSON 来测试给定的 Schema
【发布时间】:2016-06-15 05:20:54
【问题描述】:

我一直在尝试从给定架构插入文档,但无法通过 REST 客户端插入。代码粘贴如下:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var countries = require('../countries/countries.model');
var Employees = require('../Employees/Employees.model');

var countryModel = new countries();
var EmpModel = new Employees();

var City = new Schema({
    name: String,
    active: Boolean,
    countryId: {type:Schema.ObjectId, ref:countryModel},
    Employees: [{type: Schema.ObjectId, ref: EmpModel}]
});

我输入了各种样式的 JSON,但都没有成功

{
"name": "Delhi NCR",
"active": "true",
"countryId": country[0]._id,
Employees: [employees[1]._id]
}

 {
"name": "Delhi NCR",
"active": "true",
"countryId": "ObjectId(xxxxxxxxx)",
Employees: ["ObjectId(xxxxxxxxx)", "ObjectId(xxxxxxxxx)"]
}

  {
"name": "Delhi NCR",
"active": "true",
"countryId": "56dcccdddddddddaaaaaaaaa",
Employees: ["56dcccdddddddddaaaaaaaaa", "56dcccdddddddddaaaaaaaaa"]
}

但这些都不起作用。我应该输入什么 JSON。

【问题讨论】:

    标签: json mongodb api rest mongoose


    【解决方案1】:

    您正在为活动字段传递一个字符串,而不是 JSON 中的布尔值。

     {
      "name": "Delhi NCR",
      "active": true,
      "countryId": ObjectId("54cd6669d3e0fb1b302e54e4"),
       "Employees": [ObjectId("54cd6669d3e0fb1b302e54e4"), ObjectId("54cd6669d3e0fb1b302e54e4")]
     }
    

    【讨论】:

    • 像这样保存 { "_id" : ObjectId("56d6be820d4590xxxxxxxx39"), "Employees" : [], "countryId" : [], "__v" : 0 }
    【解决方案2】:

    您在架构定义中引用模型的方式不正确。 ref 选项告诉 Mongoose 在填充期间使用哪个模型,在您的情况下,您使用的是实际模型对象而不是带有模型名称的字符串值:

    var City = new Schema({
        name: String,
        active: Boolean,
        countryId: {type:Schema.ObjectId, ref: "countries"},
        Employees: [{type: Schema.ObjectId, ref: "Employees"}]
    });
    

    重新定义架构后,您可以将 _ids 从 Employees 模型作为字符串传入,因为 Mongoose 会自动将这些转换为 ObjectIds。

    "Employees": ["56dcccdddddddddaaaaaaaaa", "56dcccdddddddddaaaaaaaaa"]
    

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多