-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_start.py
More file actions
47 lines (36 loc) · 1.32 KB
/
Copy pathquick_start.py
File metadata and controls
47 lines (36 loc) · 1.32 KB
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
import asyncio
from datetime import datetime
import mongojet
import msgspec
import mongospec
from mongospec import IndexModel, MongoDocument
class User(MongoDocument):
__collection_name__ = "users"
__indexes__ = [IndexModel(keys=[("email", 1)], options={"unique": True})]
name: str
email: str
created_at: datetime = msgspec.field(default_factory=datetime.now)
async def main():
# Connect to MongoDB
mongo_client = await mongojet.create_client("mongodb://localhost:27017")
try:
# Initialize mongospec with our models
await mongospec.init(mongo_client.get_database("example_db"), document_types=[User])
# Create a new user
user = User(name="Alice", email="alice@example.com")
await user.insert()
print(f"Created user with ID: {user._id}")
# Find the user
found_user = await User.find_one({"email": "alice@example.com"})
print(f"Found user: {found_user.name} ({found_user.email})")
# Update the user
found_user.name = "Alice Smith"
await found_user.save()
print(f"Updated user name to: {found_user.name}")
# Delete the user
await found_user.delete()
print("User deleted")
finally:
# Always close the connection when done
await mongospec.close()
asyncio.run(main())