somewhere / mongodb.py
itachi-ai's picture
little update
38f5ea3 verified
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