I am new to Node.js and back-end development generally. I've already set up my server and mongoDB and connected them with my iOS app, so basically I have a userSchema and a postSchema in Node.js, a corresponding User and Post class in Objective-c. How can I initialise these two classes with the attributes I set up in Node.js?
Here is the userSchema:
var UserSchema = new mongoose.Schema({
username : String,
password : String
});
and the postSchema:
var postSchema = new mongoose.Schema({
name : String,
image : String,
description : String,
comments : [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}],
author : {
id : {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
In Xcode, I initialize the Post class like this (don't know if this is correct...but it's working):
@implementation Post
- (id)initWithDictionary:(NSDictionary *)dic
{
self = [super init];
if (self)
{
super.objectId = [dic objectForKey:@"_id"];
_name = [dic objectForKey:@"name"];
_imgURL = [dic objectForKey:@"image"];
_caption = [dic objectForKey:@"description"];
_comments = [dic objectForKey:@"comments"];
_author = [dic objectForKey:@"author"];
}
return self;
}
@end
In ViewController:
static NSString * const kMyAppBaseURLString = @"http://localhost:4000/";
@interface PostDetailViewController ()
@end
@implementation PostDetailViewController
- (void)loadData
{
NSURL* url = [NSURL URLWithString:[kMyAppBaseURLString
stringByAppendingPathComponent:[NSString stringWithFormat:@"posts/%@", postId]]];
//HTTP GET Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";
[request addValue:@"posts/json" forHTTPHeaderField:@"Accept"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (error == nil)
{
post = [[Post alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
[self.tableView reloadData];
}
}];
[dataTask resume];
}
I want to access the user's username by just post.author.username
. How do I initialize the User
class? Also, am I using the correct way to create the Post class? I am quite new to server side programming. :)