File size: 2,210 Bytes
745dedb
 
 
 
 
 
 
38f5ea3
745dedb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from pymongo import MongoClient
from bson.objectid import ObjectId
from datetime import datetime
import os
from dotenv import load_dotenv
load_dotenv()

uri = os.getenv('DATABASE_URL_')
client = MongoClient(uri)
db = client["blog_db"]  # Create a database called blog_db
collection = db["posts"]  # Create a collection called posts


# Function to add a new post
def add_post(title, content, status, username):
    now = datetime.utcnow()
    post = {
        "title": title,
        "content": content,
        "createdAt": now,
        "updatedAt": now,
        "status": status,
        "auther": username
    }
    collection.insert_one(post)
    return "Post added successfully!"


# Function to update a post
def update_post(post_id, title, content, status):
    # Ensure post_id is a valid ObjectId
    try:
        post_id = ObjectId(post_id)
    except Exception as e:
        return f"Invalid post ID: {str(e)}"

    # Update the post in the collection
    result = collection.update_one({"_id": post_id}, {"$set": {"title": title,
                                                               "content": content,
                                                               "status": status,
                                                               "updatedAt": datetime.utcnow(),

    }})

    if result.matched_count == 1:  # Check if a document was found and updated
        return "Post updated successfully!"
    else:
        return "Post not found or no changes were made."

# Function to delete a post
def delete_post(post_id):
    collection.delete_one({"_id": ObjectId(post_id)})
    return "Post deleted successfully!"


# Function to get all posts (just titles for the sidebar)
def get_post_titles(status):
    titles = collection.find(
        {"status": status},  # Filter by status
              {"_id": 1, "title": 1}  # Get only title and _id
              ).sort("createdAt", -1)  # Sort by createdAt in descending order (latest first)

    return titles


# Function to get a specific post by id
def get_post_by_id(post_id):
    post = collection.find_one({"_id": ObjectId(post_id)})
    return post