Reputation: 2732
I am using MongoDB in my Sails setup to store my collections.
I am making a POST request through an API, whose request body looks like this :
**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
}
}
This record is to be stored in my mongodb collection named "leads". My "Leads" model looks like this:
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"
}
}
};
The associated "Lead_campaign_detail" model is as following
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"
}
}
};
And My controller handler is:
create_lead_api:function(req, res){
Leads.create(params, function(err, resp){
if(err) return res.negotiate(err);
else return res.json(resp);
})
},
WHAT I HAVE TRIED
1> I tried using .native()
. It creates a new record BUT it does not care about the attributes in the model "Leads" or the other one. It just saves as the request is.
2> Tried creating using the .create()
. It does not stores the nested values of index "campaign" in the request: the stored value looks like this:
{ **IN MY DB it looks like**
"name": "martin",
"phone": "5447874787",
"comment": "This is a comment",
"campaign": "579083f049cb6ad522a6dd3c",
"id": "579083f049cb6ad522a6dd3d"
}
I WANT TO
1> Store the record in the same format as the requested am sending.
2> Make use of the waterline ORM function .create()
to achieve the same if possible.
3> .native()
is also in option if my Model-attributes:{} can be used to bring in between before storing the record. I want to store only values defined in attributes:{ }
Any help is appreciated, Google is failing me. Thanks
Upvotes: 1
Views: 685
Reputation: 620
If you want the document in 'leads' collection to look like your request body, then you should use:
campaign: {
type: "json"
}
in your 'Leads' model, rather than linking to 'lead_campaign_detail' collection. You can then do away with the 'lead_campaign_detail' model.
By saying model: 'lead_campaign_detail'
you are essentially linking the "Leads" document to "lead_campaign_detail", See Waterline One-way association and populate() for more details.
Upvotes: 2