Sails.js + Mongodb使用ORM插入一个嵌套的jsonlogging
我在我的Sails设置中使用MongoDB来存储我的集合。
我通过一个API发出一个POST请求,其请求体看起来像这样:
**THE REQUEST BODY** { "name":"Martin", "phone":"5447874787", "comment":"This is a comment", "campaign":{ "campaign_id":123454587, "name":"Digital Marketing", "category":"Marketing", "sub_category":"Digital", "product_name":"no product", "product_id":5417 } }
这个logging将存储在我的名为“leads”的 mongodb集合中。 我的“潜在顾客”模型如下所示:
module.exports = { schema: true, attributes:{ name:{ required:true, type:"string", unique: true }, phone:{ type:"string" }, comment:{ type:"string" }, campaign:{ model: 'lead_campaign_detail', // via: "lead_model" } } };
相关的“Lead_campaign_detail”模型如下
module.exports = { attributes:{ campaign_id:{ required:true, type:'integer' }, name:{ type:"string" }, category:{ type:"string" }, sub_category:{ type:"string" }, product_name:{ type:"string" }, product_id:{ type:"integer" } } };
而我的控制器处理程序是:
create_lead_api:function(req, res){ Leads.create(params, function(err, resp){ if(err) return res.negotiate(err); else return res.json(resp); }) },
我试过了什么
1>我尝试使用.native()
。 它会创build一个新的logging,但它不关心模型“Leads”中的属性或另一个。 它只是保存请求。
2>尝试使用.create()
创build。 它不会在请求中存储索引“campaign”的嵌套值:存储的值如下所示:
{ **IN MY DB it looks like** "name": "martin", "phone": "5447874787", "comment": "This is a comment", "campaign": "579083f049cb6ad522a6dd3c", "id": "579083f049cb6ad522a6dd3d" }
我要
1>以与请求发送相同的格式存储logging。
2>使用水线ORM函数.create()
尽可能实现相同的function。
3> .native()
也可以select,如果我的模型属性:{}可以在存储logging之前使用。 我只想存储在属性中定义的值:{}
任何帮助表示赞赏,谷歌是失败的我。 谢谢
如果您希望“潜在客户”集合中的文档看起来像您的请求主体,那么您应该使用:
campaign: { type: "json" }
在您的“潜在顾客”模式中,而不是链接到“lead_campaign_detail”集合。 然后,您可以废除“lead_campaign_detail”模型。
通过说model: 'lead_campaign_detail'
您基本上将“Leads”文档链接到“lead_campaign_detail”,请参阅Waterline单向关联和填充()以获取更多详细信息。