您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

手把手教你使用Node连接mongodb

2024/3/31 13:56:37发布30次查看
要使用 node.js 连接 mongodb,通常使用 mongoose 这个对象文档模型(odm)库。下面就来简单介绍一下使用 mongoose 连接 mongodb 的方法。
mongoose 是一个 node.js 包,提供了一个使用 mongo 数据库的接口。在应用程序中使用它是非常轻量级的 npm 包。 mongoose 拥有所有方法集,可以连接和访问存储在 mongo 数据库中的数据。
react-giant:一个react+next.js+mongodb的学习项目。
安装mongoose库这是 node.js 项目开发必须的步骤之一,使用 npm 命令进行安装,在终端输入以下命令即可安装:
npm install mongoose --save
连接 mongodb通常在使用数据库的时候,都需要先建立连接,通过以下方式建立连接:
const mongoose = require("mongoose");const connectdb = async () => { await mongoose.connect("mongodb://localhost:27017/admin");};connectdb();
在上面的代码中,mongoose.connect() 函数用于建立到mongodb的连接。第一个参数指定了mongodb的连接url,格式为 mongodb://<host>:<port>/<database-name>?<options>,其中<host> 指定mongodb所在的主机名或ip地址,<port>指定mongodb的端口号,<database-name> 指定要连接的数据库的名称,<options>是一些配置项,以参数的方式传递,如 ?usenewurlparser=true&useunifiedtopology=true。对于需要用户名和密码连接的数据库,则<host>参数方式为 username:password@127.0.0.1:27017。【相关教程推荐:nodejs视频教程、编程教学】
需要注意的是,mongoose 不同版本连接方式上有点区别,上述代码是在版本 7.0.2 可以正常使用。
定义模型和模式在使用 mongoose 时,通常需要先定义一个模型和对应的模式。模型是指 mongodb 中的一个集合,而模式则指定了集合中每个文档的结构和字段。以下是一个简单的模式定义示例:
const mongoose = require("mongoose");const userschema = new mongoose.schema({ username: { type: string, required: true, }, email: { type: string, required: true, unique: true, maxlength: [255, "email length must be at most 255"], }, ip: { type: string, required: true, },});const user = mongoose.model("user", userschema);
crud操作在定义了模型和模式之后,就可以使用模型进行 crud(创建、读取、更新、删除)操作。以下是一些常用的示例代码:
const mongoose = require("mongoose");// 创建记录async function createusers() { const result = await user.create({ username: "quintion", email: "quintiontang@gmail.com", ip: "127.0.0.1", }); return result;}// 查询文档列表async function getusers() { const users = await user.find(); return users;}// 查询单个async function getuser() { const user = await user.find({ username: "quintion", }); return user;}// 删除记录async function deleteuser() { return await user.remove({ username: "quintion", });}
上述代码只是一个简单的示例,如果需要一个完整的可运行的代码,可以查看下面的项目:
react-giant:一个react+next.js+mongodb的学习项目。
更多node相关知识,请访问:nodejs 教程!
以上就是手把手教你使用node连接mongodb的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product