【问题标题】:How do I need to add a Json file according to these code?我需要如何根据这些代码添加 Json 文件?
【发布时间】:2017-05-06 06:57:21
【问题描述】:

大家好,我不知道如何根据这些代码添加json文件。
我想创建一个包含姓名、姓氏、年龄、电话、mevki_id、城市和城镇的用户。

注意:城市和城镇在土耳其语 ililce 中的意思。

这是我的代码:

用户架构:

var userSchema = Mongoose.Schema({ 

    name:{type: String,require:true},
    surname: {type: String,require:true},
    tel: {type: String,require:true},
    age: {type: String,require:true},
    mevki_id: {type: String,require:true},
    location_id : { type : Mongoose.Schema.Types.ObjectId , ref: 'locations'}

位置架构:

var LocationSchema = Mongoose.Schema ({

    il: {type: String, require:true},

    ilce: {type:String, require:true}   

});

用户控制器:

this.createUser = function (req, res, next) {


      user.name = req.body.name;
        user.surname = req.body.surname;
        user.tel = req.body.tel;
        user.age = req.body.age;
        user.mevki_id= req.body.mevki_id;           
      user.location_id=location._id.id;

 user.save(function(err, result) {


        if (err) {

            return res.send({'error':err}); 
        }
        else {
    return res.send({'result':result,'status':'successfully saved'});
  }
    });
};

我需要用 postman 插入什么样的 json 文件??

【问题讨论】:

  • 我不确定你在问什么。您希望 JSON 文件将用户添加到您的数据库吗?
  • 是的,我想要这个,但实际上我不知道我想知道如何向用户添加文档城市和城镇信息,因为用户模式中没有城市和数据,它们在位置模式中所以什么样将 json 文件添加到我的数据库中?谢谢 :)

标签: node.js mongodb mongoose reference postman


【解决方案1】:

很明显,您的 POST 查询数据应该以这种格式发送:

{
    name: 'name',
    surname: 'surname',
    tel: 'tel',
    age: 'age',
    mevki_id: 'mevki_id',
    location_id: 'location_id'
}

我无法确定控制器中的 location._id.id 变量,因为您没有显示它的来源(在代码的早期?),但您需要传递位置 id作为对数据库中某个位置的引用,对应于 userSchema location_id 类型。
id 是对从 LocationSchema 定义的位置的 ObjectId 引用。
您可以省略此元素,因为它在架构中不是必需的

请记住,架构只是数据的结构,而不是数据本身。

【讨论】:

  • 我真的很感谢你 TGrif,你真的是个乐于助人的人
  • 如果要感谢他,记得验证答案;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多