node.js 操作 MongoDB

Node.js 如何连接 MongoDB?

使用 Mongoose ODM 工具
复制代码
npm install mongoose
建立连接
复制代码
// db.js
const mongoose = require("mongoose");
 
mongoose.connect("mongodb://127.0.0.1:27017/mydb")
  .then(() => console.log("MongoDB 连接成功"))
  .catch((err) => console.error("MongoDB 连接失败", err));

说明:

  • 127.0.0.1:27017 是 MongoDB 默认端口
  • mydb 是数据库名,不存在会自动创建

定义数据模型(Model)

复制代码
// model/UserModel.js
const mongoose = require("mongoose");
 
const UserSchema = new mongoose.Schema({
  username: String,
  password: String,
  age: Number
});
 
const UserModel = mongoose.model("user", UserSchema); // 对应集合 users
module.exports = UserModel;

Node.js 操作 MongoDB(CRUD)

所有操作需在 await connect() 后使用,或包裹在 async 函数中。

1️ 添加数据(Create)
复制代码
await UserModel.create({
  username: "Tom",
  password: "123456",
  age: 20
});

查询数据(find)

查询全部

复制代码
const users = await UserModel.find(); 

条件查询

复制代码
const users = await UserModel.find({ age: { $gte: 18 } });

查询一条

复制代码
const user = await UserModel.findOne({ username: "Tom" });
更新数据(Update)
复制代码
await UserModel.updateOne(
  { username: "Tom" },
  { $set: { age: 25 } }
);
删除数据(Delete)
复制代码
await UserModel.deleteOne({ username: "Tom" });

index.js 示例:

复制代码
const connect = require('./db');
const UserModel = require('./model/UserModel');
 
async function main() {
  await connect();
 
  // 添加
  await UserModel.create({ username: "Alice", password: "123", age: 22 });
 
  // 查询
  const users = await UserModel.find();
  console.log(users);
 
  // 更新
  await UserModel.updateOne({ username: "Alice" }, { age: 23 });
 
  // 删除
  await UserModel.deleteOne({ username: "Alice" });
 
  process.exit();
}
 
main();

总结

项目 内容

数据库 MongoDB(非关系型,文档型)

Node连接方式 mongoose.connect()

操作方式 create、find、updateOne、deleteOne

工具推荐 MongoDB Compass、Robo 3T、NoSQLBooster 等

数据结构 文档(Document)、集合(Collection)

常见端口 默认 27017

相关推荐
he___H1 天前
Redis高级数据类型
数据库·redis·缓存
霖霖总总1 天前
[小技巧60]深入解析 MySQL Online DDL:MySQL Online DDL、pt-osc 与 gh-ost 机制与最佳实践
数据库·mysql
爱学习的阿磊1 天前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
惊讶的猫1 天前
Redis双写一致性
数据库·redis·缓存
怣501 天前
[特殊字符] MySQL数据表操作完全指南:增删改查的艺术
数据库·mysql·adb
安然无虞1 天前
「MongoDB数据库」初见
数据库·mysql·mongodb
一起养小猫1 天前
Flutter for OpenHarmony 实战:番茄钟应用完整开发指南
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
Mr_Xuhhh1 天前
MySQL视图详解:虚拟表的创建、使用与实战
数据库·mysql
AI_56781 天前
MySQL索引优化全景指南:从慢查询诊断到智能调优
数据库·mysql
老虎06271 天前
Redis入门,配置,常见面试题总结
数据库·redis·缓存