Mongoose
是 Node.js的ODM库。
和Sequelize类似,Mongoose提供了node.js对于MongoDB进行操作的便利。
安装
使用
- 连接MongoDB
js1 2 3 4 5 6 7 8 9
| const mongoose = require("mongoose");
mongoose .connect("mongodb://localhost:27017/mydatabase", { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log("Connected to MongoDB")) .catch((err) => console.error("Could not connect to MongoDB...", err));
|
- 定义Schema
Mongoose中使用Schema来定义文档结构。
js1 2 3 4 5 6
| const userSchema = new mongoose.Schema({ name: { type: String, required: true }, age: Number, email: { type: String, required: true, unique: true }, created_at: { type: Date, default: Date.now } });
|
- 创建模型Model
使用以上创建好的Schema来创建模型Model。
js1
| const User = mongoose.model('User', userSchema);
|
- 创建和保存
使用上面创建好的Model可以对数据进行CRUD。
js1 2 3 4 5 6 7 8 9 10 11
| const user = new User({ name: 'John Doe', age: 30, email: 'johndoe@example.com' });
user.save() .then(doc => console.log('User saved:', doc)) .catch(err => console.error('Error saving user:', err));
|
- 关闭连接
js1
| mongoose.connection.close();
|
CRUD
js1 2 3 4 5
| const user = new User({ name: 'John Doe', age: 30, email: 'johndoe@example.com' });
|
js1 2 3 4 5 6 7
| User.findOne({ name: 'John Doe' }) .then(user => console.log('User found:', user)) .catch(err => console.error('Error finding user:', err));
User.find({ name: 'John Doe' }) .then(users => console.log('Users found:', users)) .catch(err => console.error('Error finding users:', err));
|
js1 2 3 4 5 6 7 8 9 10 11
| User.updateOne({ name: 'John Doe' }, { age: 31 }) .then(result => console.log('User updated:', result)) .catch(err => console.error('Error updating user:', err));
User.updateMany({ name: 'John Doe' }, { age: 31 }) .then(result => console.log('User updated:', result)) .catch(err => console.error('Error updating user:', err));
User.findByIdAndUpdate(userId, { age: 27 }, { new: true }) .then(user => console.log('Updated user:', user)) .catch(err => console.error('Error updating user:', err));
|
js1 2 3 4 5 6 7
| User.deleteOne({ name: 'John Doe' }) .then(result => console.log('User deleted:', result)) .catch(err => console.error('Error deleting user:', err));
User.findByIdAndDelete(userId) .then(user => console.log('Deleted user:', user)) .catch(err => console.error('Error deleting user:', err));
|
中间件
Mongoose还支持使用中间件(middleware)来执行一些预处理或后处理操作。
js1 2 3 4 5
| userSchema.pre('save', function(next) { console.log('Before saving a user'); next(); });
|
参考
- https://mongoosejs.net/
- https://mongoosejs.com/