Node.js 后端开发之使用 Mongoose 连接 MongoDB 数据库
Hello World
配置文件:
.env
MONGO_URI='xxx'
服务端:
// server.js
const express = require("express");
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const app = express();
dotenv.config();
// 连接 MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('MongoDB Connection Error:', err);
});
// 设置 Schema(表模板)
const personSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
favoriteFoods: [String]
});
// 生成 Model(表)
const Person = mongoose.model("Person", personSchema);
// 添加中间件,用于解析请求体
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 处理路由
app.post('/new', async (req, res) => {
try {
let person = req.body;
console.log('Request Body:', person);
person = new Person(person);
const result = await person.save(); // 需要等待操作完成
res.json(result);
} catch (err) {
console.error('Error: ', err.message);
res.status(500).json({
error: 'Server Error',
message: err.message
});
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
使用 Axios 发送一个请求:
// client.js
const axios = require('axios');
const data = {
name: "Jane Fonda",
age: 84,
favoriteFoods: ["eggs", "fish", "fresh fruit"]
};
axios.post('http://localhost:3000/new', data)
.then(response => {
console.log('Response:', response.data);
})
.catch(error => {
console.error('Error:', error.response.data);
});
常用函数
Model.deleteMany()
Model.deleteOne()
Model.find()
Model.findById()
Model.findByIdAndDelete()
Model.findByIdAndRemove()
Model.findByIdAndUpdate()
Model.findOne()
Model.findOneAndDelete()
Model.findOneAndReplace()
Model.findOneAndUpdate()
Model.replaceOne()
Model.updateMany()
Model.updateOne()
参见:Queries
链式搜索:
Model.find({ age: 55 })
.sort({ name: -1 })
.limit(5)
.select({ favoriteFoods: 0 })
.exec((error, data) => {
//do something here
});
参见:Chain Search Query Helpers to Narrow Search Results | freeCodeCamp.org
Mongoose 参考文档:Mongoose: Getting Started