Please give me a simple MVC program using express mongoose winstron boday-paser . Also provide views ChatGPT ChatGPT Sure! Below is a simple example of a Node.js application using Express.js as the web framework, Mongoose as the MongoDB object modeling tool, and EJS as the view engine. We'll create a basic MVC (Model-View-Controller) structure for a simple todo list application.

First, make sure you have Node.js and npm (Node Package Manager) installed on your system.

Initialize your project: bash コードをコピーする mkdir todo-app cd todo-app npm init -y Install dependencies: bash コードをコピーする npm install express mongoose ejs body-parser Create the project structure: plaintext コードをコピーする todo-app/ ├── controllers/ │ └── todoController.js ├── models/ │ └── Todo.js ├── views/ │ └── index.ejs └── app.js Now, let's create the MVC components: models/Todo.js javascript コードをコピーする const mongoose = require('mongoose');

const todoSchema = new mongoose.Schema({ task: { type: String, required: true }, completed: { type: Boolean, default: false } });

const Todo = mongoose.model('Todo', todoSchema);

module.exports = Todo; controllers/todoController.js javascript コードをコピーする const Todo = require('../models/Todo');

exports.getTodos = async (req, res) => { try { const todos = await Todo.find(); res.render('index', { todos }); } catch (err) { console.error(err); res.status(500).send('Server Error'); } };

exports.createTodo = async (req, res) => { try { await Todo.create({ task: req.body.task }); res.redirect('/'); } catch (err) { console.error(err); res.status(500).send('Server Error'); } }; views/index.ejs html コードをコピーする

Todo App

Todo List

app.js javascript コードをコピーする const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const todoController = require('./controllers/todoController');

const app = express();

// Connect to MongoDB mongoose.connect('mongodb://localhost/todo_app', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }).then(() => { console.log('MongoDB Connected'); }).catch(err => { console.error(err); });

// Set up body-parser app.use(bodyParser.urlencoded({ extended: true }));

// Set up view engine app.set('view engine', 'ejs'); app.set('views', './views');

// Routes app.get('/', todoController.getTodos); app.post('/', todoController.createTodo);

// Start server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(Server is running on port ${PORT}); }); That's it! You now have a basic todo list application using Express.js, Mongoose, and EJS with a simple MVC structure. You can run the application using node app.js command in your terminal and access it at http://localhost:3000.