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

相关推荐
NocoBase18 分钟前
【2.0 教程】第 1 章:认识 NocoBase ,5 分钟跑起来
数据库·人工智能·开源·github·无代码
Hoshino.412 小时前
基于Linux中的数据库操作——下载与安装(1)
linux·运维·数据库
Oueii3 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
未来龙皇小蓝4 小时前
【MySQL-索引调优】11:Group by相关概念
数据库·mysql·性能优化
2401_831824964 小时前
使用Fabric自动化你的部署流程
jvm·数据库·python
njidf4 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
twc8294 小时前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
@我漫长的孤独流浪4 小时前
Python编程核心知识点速览
开发语言·数据库·python
2401_851272994 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
枕布响丸辣4 小时前
MySQL 从入门到精通:完整操作手册与实战指南
数据库·mysql