【发布时间】:2016-07-21 10:39:02
【问题描述】:
我在 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
}
}
此记录将存储在我的名为 “leads” 的 mongodb 集合中。我的“Leads”模型如下所示:
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()。它创建了一条新记录,但它不关心模型“Leads”或另一个中的属性。它只是按请求保存。
2> 尝试使用 .create() 创建。它不会在请求中存储索引 "campaign" 的嵌套值:存储的值如下所示:
{ **IN MY DB it looks like**
"name": "martin",
"phone": "5447874787",
"comment": "This is a comment",
"campaign": "579083f049cb6ad522a6dd3c",
"id": "579083f049cb6ad522a6dd3d"
}
我想要
1>以与请求发送时相同的格式存储记录。
2>尽可能使用水线 ORM 函数 .create() 来实现同样的效果。
3> .native() 如果我的 Model-attributes:{} 可用于在存储记录之前引入两者之间,则也可以选择。我只想存储属性中定义的值:{ }
感谢您的帮助,Google 让我失望了。 谢谢
【问题讨论】:
-
您希望“潜在客户”集合中的最终文档看起来如何?
-
请求正文的格式相同(嵌套一个):{ "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 } }
标签: javascript json node.js mongodb sails.js