Created
August 3, 2015 06:33
-
-
Save sht5/50fa7927cff548e13a09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MongoDB.Bson; | |
using MongoDB.Bson.Serialization.Attributes; | |
using MongoDB.Driver; | |
using MongoDB.Driver.Linq; | |
using softwareBlogREST.Models; | |
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using System.Web.Http; | |
using System.Web.Http.Cors; | |
namespace softwareBlogREST.Controllers | |
{ | |
#if DEBUG | |
[EnableCors(origins: "http://localhost:9000",headers:"*",methods:"*")] | |
#else | |
[EnableCors(origins: "http://mydomain.net", headers: "*", methods: "*")] | |
#endif | |
public class PostController : ApiController | |
{ | |
protected static MongoClient client; | |
protected static IMongoDatabase db; | |
[HttpGet] | |
[ActionName("GetTopTenPostsFromMongoDB")] | |
public async Task<List<Post>> GetTopTenPostsFromMongoDB(int amountOfPagesLoaded) | |
{ | |
var db = MongoDatabase.GetDatabase(); | |
var collection = db.GetCollection<Post>("Posts"); | |
//SortDefinition<Post> sortDef = "{ dateCreated: 1 }"; | |
var sortDef = Builders<Post>.Sort.Descending("dateCreated"); | |
var documents = await collection.Find(new BsonDocument()).Sort(sortDef).Skip((amountOfPagesLoaded)*10).Limit(10).ToListAsync(); | |
return documents.FindAll(_ => true); | |
} | |
[HttpGet] | |
[ActionName("GetPostByName")] | |
public async Task<Post> GetPostByName(String postName) | |
{ | |
var db = MongoDatabase.GetDatabase(); | |
var collection = db.GetCollection<Post>("Posts"); | |
var documents = await collection.Find(new BsonDocument()).ToListAsync(); | |
return documents.FindLast(post => post.postTitle.ToLower().Contains(postName.ToLower())); | |
} | |
[HttpGet] | |
[ActionName("addCommentToPost")] | |
public async Task<int> addCommentToPost(string postID,string user, string message, DateTime date) | |
{ | |
var db = MongoDatabase.GetDatabase(); | |
var collection = db.GetCollection<Post>("Posts"); | |
var filter = Builders<Post>.Filter.Eq("_id",new ObjectId(postID)); | |
softwareBlogREST.Models.Post.Comment newComment = new softwareBlogREST.Models.Post.Comment(); | |
newComment.message = message; | |
newComment.dateCreated = date; | |
newComment.numOfLikes = 0; | |
newComment.user = user; | |
var result = await collection.UpdateOneAsync(filter, Builders<Post>.Update.Push(x => x.comments, newComment)); | |
return 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment