【问题标题】:How to handle embedded json in Sails js如何在 Sails js 中处理嵌入的 json
【发布时间】:2014-03-12 02:52:42
【问题描述】:

有没有办法从 Sails.js 控制器中的嵌入式 json 创建相关对象?

在正在创建的类的控制器中,我需要在不同的类中创建相关记录,并包含刚刚创建的父记录的 id。

“子”记录的数据嵌入在创建父记录的 json 中。使用的数据库是 Mongo,因此它不强制执行关系。

如何创建这些相关对象?

任何示例供参考将不胜感激。

更新:

我已经实现了第一个答案中的更改,现在收到错误“[TypeError: Cannot call method 'all' of undefined]”

有什么想法吗?

编辑添加代码:

采购信息模型

module.exports = {

attributes: {

parent_account:{
    type:'string'
},

  purchase_date:{
      type:'datetime'
  },

  product:{
      type:'string'
  },

  subscription_length:{
      type:'integer'
  },

  renewal_date:{
      type:'date'
  },

  users_authorized:{
      type:'integer'
  },

  users_activated:{
      type:'integer'
  },

  company_name:{
      type:'string'
  },

  company_contact:{
      type:'string'
  },

  company_email:{
      type:'string',
      required:true,
      email:true
  },

  company_phone:{
      type:'string'
  },

  intended_use:{
      type:'string'
  },

  // reference to company
  company:{
      collection: 'company',
      via:'purchaser'
  }
}

};

公司模式

module.exports = {


attributes: {

company_name:{
    type:'string',
    required:'true'
},

  main_addr1:{
      type:'string',
      required:'true'
  },

  main_addr2:{
      type:'string',
      required:'true'
  },

  main_city:{
      type:'string',
      required:'true'
  },

  main_state:{
      type:'string',
      required:'true'
  },

  main_zip:{
      type:'string',
      required:'true'
  },

  main_country:{
      type:'string',
      required:'true'
  },

  mailing_same_as_main:{
      type:'boolean'
  },

  mailing_addr1:{
      type:'string'
  },

  mailing_addr2:{
      type:'string'
  },

  mailing_city:{
      type:'string'
  },

  mailing_state:{
      type:'string'
  },

  mailing_zip:{
      type:'string'
  },

  mailing_country:{
      type:'string'
  },

  primary_contact:{
      type:'string'
  },

  company_email:{
      type:'string',
      required:true,
      email:true
  },

  purchaser: {
      model: 'purchaseinfo'
  }

}

};

PurchaseInfo 控制器

module.exports = {

  create: function(res, req){
  var purchaseData = req.params.all();

  // Extract the company info from the POSTed data
  var companyData = purchaseData.company_info;

 // Create the new Purchase record
  PurchaseInfo.create(purchaseData).exec(function(err,newPurchaseInfo){
      if (err){return res.req.serverError(err);}

      // Create the new Company, linking it to the purchase
      companyData.purchaser = newPurchaseInfo.id;
      Company.create(companyData).exec(function(err, newCompany) {
          if (err) {return res.serverError(err);}
          return res.json(newPurchaseInfo);
      })
  })
},
_config: {}
};

发布

http://localhost:1337/purchaseinfo/create
body:
{   "parent_account": 1,    "purchase_date": "2014-03-03",  "product": "C V1",  "subscription_length": 12,  "renewal_date": "2015-03-03",   "users_authorized": 10,     "users_activated": 1,   "company_name": "Bob's Trucking",   "company_contact": "Jane Smith",    "company_email":"jsmith@bobstrucking.com",  "company_phone": 5035129657,    "intended_use": "trucking",     "company_info": {       "company_name": "Bob's Trucking",       "main_addr1": "101 First Street",       "main_city": "Portland",        "main_state": "OR",         "main_zip": "97230",        "main_country": "USA",      "mailing_same_as_main":"true",      "primary_contact": "Jane Smith",        "company_email": "info@bobstrucking.com"    } }

【问题讨论】:

    标签: javascript express sails.js


    【解决方案1】:

    Sails v0.10 允许您在模型之间创建关联。这是UserPet 模型的简单示例:

    /* api/models/User.js */
    module.exports = {
       attributes: {
         name: 'string',
         pets: {
            collection: 'pet',
            via: 'owner'
         }
       }
    };
    

    /* api/models/Pet.js */
    module.exports = {
       attributes: {
         name: 'string',
         breed: 'string',
         owner: {
            model: 'user'
         }
       }
    };
    

    /* api/controllers/UserController.js */
    module.exports = {
    
      create: function(req, res) {
    
        // Assuming the POST contains all the data we need to create a user...
        var userData = req.params.all();
        // Extract the pet from the POSTed data
        var petData = userData.pet;
        // Delete the pet from the POSTed data, if you
        // don't want it saved to the User collection in Mongo
        delete userData.pet;
        // Create the new user
        User.create(userData).exec(function(err, newUser) {
           if (err) {return res.serverError(err);}
           // Create the new pet, linking it to the user
           petData.owner = newUser.id;
           Pet.create(petData).exec(function(err, newPet) {
              if (err) {return res.serverError(err);}
              return res.json(newUser);
           });
    
        });
    
      }
    };
    

    此代码包含对 User 的默认 create 蓝图操作的覆盖;你也可以为它创建一个单独的控制器动作。实际上,您可能还想检查宠物是否已经存在,进行其他验证等。但这应该会让您顺利上路!

    【讨论】:

    • 斯科特,感谢您的出色回复!我试过了,但还不能让它工作。我一直在有效地“无法阅读未定义的宠物”。所以看起来身体没有被解析。此外,我在“serverError”引用中遇到错误。这些属于 Sails 还是属于您的职能?再次感谢您的帮助!
    • 抱歉,已编辑答案以指定这一切都在最新版本的 Sails 中,您可以通过 from Github 或通过 npm install sails@beta 获得。虽然res.serverError 应该可以在 v0.9.x 中使用...
    • 还将 req.body 更改为 req.params.all(),这会生成 所有 发送到路由的参数的哈希。
    • 太棒了!我今晚回家时会检查一下。再次感谢!
    • 在 Scott 的帮助下,我得以完成这项工作!谢谢斯科特。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2023-04-08
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多