const DBName = "EMI_SOCIAL"; const Post = require("./../def/post.js") postDB = (DB)=>{ DB.postCols = DB.db.db(DBName).collection("posts"); DB.newPost = (postObj) => { return DB.postCols.insertOne(postObj.toObj()).catch((err)=>{ console.log(err); return false; }); } DB.newReaction = (postid, profileid, reaction) => { const id = DB.ObjectID(postid); let update = { $set:{ ["reactions." + profileid]: reaction, lastUpdated: new Date() } } return DB.postCols.updateOne({_id: id}, update).catch((err)=>{ console.log(err); return false; }); } DB.removeReaction = (postid, profileid) => { const id = DB.ObjectID(postid); let update = { $unset:{ ["reactions." + profileid]: "" }, $set: { lastUpdated: new Date() } } return DB.postCols.updateOne({_id: id}, update).catch((err)=>{ console.log(err); return false; }); } DB.bookmarkPost = async (postid, profileId)=>{ const _id = DB.ObjectID(postid); let update = { $addToSet:{ bookmarks: DB.ObjectID(profileId) } } return DB.postCols.updateOne({_id}, update).catch((err)=>{ console.log(err); return false; }); } DB.unbookmarkPost = async (postid, profileId)=>{ const _id = DB.ObjectID(postid); let update = { $pull:{ bookmarks: DB.ObjectID(profileId) } } return DB.postCols.updateOne({_id}, update).catch((err)=>{ console.log(err); return false; }); } DB.newComment = (postid, comment) => { const id = DB.ObjectID(postid); return DB.postCols.updateOne({_id: id}, { $push: { comments: comment }, $set: { lastUpdated: new Date() } }).catch((err)=>{ console.log(err); return false; }); } DB.newCommentReaction = (postid, commentDate, userid, reaction) => { const id = DB.ObjectID(postid); let update = { $set:{ ["comments.$.reactions." + userid]: reaction, "comments.$.lastUpdated": new Date(), lastUpdated: new Date() } } return DB.postCols.updateOne({ _id: id, "comments.createdAt": commentDate }, update).catch((err)=>{ console.log(err); return false; }); } DB.getPosts = (profileId) => { let query = {}; if(profileId) { const id = DB.ObjectID(profileId); query = { $or: [ {profileid: id}, {toProfile: id} ] }; } return DB.postCols.find(query).sort({_id: -1}).toArray().catch((err)=>{ console.log(err); return false; }); } DB.getFeed = async (profileId) => { const profile = await DB.getProfile(profileId); let ids = profile.following.map((id)=>DB.ObjectID(id)); ids.push(profileId) const _id = DB.ObjectID(profileId); query = { $or: [ {profileid: { $in: ids }}, {toProfile: { $in: ids }} ] }; return DB.postCols.find(query).sort({lastUpdated: -1}).limit(20).toArray().catch((err)=>{ console.log(err); return false; }); } DB.getPostsOfUser = (userId) => { let userid = DB.ObjectID(userId); return DB.postCols.find({userid}).sort({_id: -1}).toArray().catch((err)=>{ console.log(err); return false; }); } DB.getPost = (postId) => { let _id = DB.ObjectID(postId); return DB.postCols.findOne({_id}).catch((err)=>{ console.log(err); return false; }); } } module.exports = postDB;