Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 🥇 Step 1: Finalize backend using MongoDB & Mongoose

- [ ] Create a `Thought` model in `models/Thought.js`
- [x] Create a `Thought` model in `models/Thought.js`
- Fields: `message` (string, required, min/max length), `hearts`, `createdAt`
- [ ] Seed the database with sample thoughts
- [ ] Create route: `GET /thoughts` → return latest (e.g. 20)
Expand Down
2 changes: 0 additions & 2 deletions controllers/thoughtsController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { v4 as uuidv4 } from "uuid";

// controllers/thoughtsController.js
import loadThoughts from "../utils/loadThoughts.js";
import saveThoughts from "../utils/saveThoughts.js";
Expand Down
22 changes: 22 additions & 0 deletions models/Thought.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import mongoose from "mongoose";

const ThoughtSchema = new mongoose.Schema({
message: {
type: String,
required: [true, "A message is required"],
minlength: [5, "A message must be at least 5 characters long"],
maxlength: [140, "A message can't be longer than 140 characters"],
trim: true,
},
hearts: {
type: Number,
default: 0,
min: [0, "Hearts cannot be negative"],
},
createdAt: {
type: Date,
default: Date.now,
},
});

export const Thought = mongoose.model("Thought", ThoughtSchema);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@babel/node": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"express": "^4.17.3",
"express-list-endpoints": "^7.1.1",
"nodemon": "^3.0.1"
Expand Down
26 changes: 26 additions & 0 deletions utils/seedThoughts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import mongoose from "mongoose";
import dotenv from "dotenv";
import fs from "fs";
import { Thought } from "../models/Thought.js";

dotenv.config();

const mongoUrl =
process.env.MONGO_URL || "mongodb://localhost:27017/happyThoughts";
mongoose.connect(mongoUrl);

const thoughtData = JSON.parse(fs.readFileSync("./data/data.json"));

const seedDatabase = async () => {
try {
await Thought.deleteMany();
await Thought.insertMany(thoughtData);
console.log(`🌱 Successfully seeded ${thoughtData.length} thoughts!`);
} catch (err) {
console.error("❌ Seeding error:", err);
} finally {
mongoose.disconnect();
}
};

seedDatabase();