Nodejs使用express連接數(shù)據(jù)庫mongoose的示例
前面需要準(zhǔn)備的內(nèi)容可看前面的文章:
連接 mongoose數(shù)據(jù)庫需要使用 Node.js 的 mongoose驅(qū)動(dòng)程序。在 Express 應(yīng)用程序中使用 mongoose驅(qū)動(dòng)程序時(shí),需要執(zhí)行以下步驟
先創(chuàng)建一個(gè)js文檔
db.js文檔
安裝 MongoDB 驅(qū)動(dòng)程序:
在你的項(xiàng)目目錄下使用 npm 或 yarn 安裝 mongoose驅(qū)動(dòng)程序。
npm install mongoose
引入 MongoDB 模塊:
在 Express 應(yīng)用程序的文件中引入 MongoDB 模塊。
const mongodb = require('mongoose');
設(shè)置數(shù)據(jù)庫連接:
創(chuàng)建一個(gè) mongoose客戶端,并通過客戶端連接到 mongoose數(shù)據(jù)庫。
const mongoose = require('mongoose'); // mongoose連接字符串,包括數(shù)據(jù)庫地址和名稱 mongoose.connect('mongodb://localhost:27017/mydatabase') .then(() => { console.log('Connected to the database'); }) .catch((err) => { console.error('Failed to connect to the database:', err); });
在上面的代碼中,uri
變量包含了 mongoose數(shù)據(jù)庫的連接字符串,其中包括數(shù)據(jù)庫地址和名稱。然后,創(chuàng)建一個(gè)新的 mongoose
實(shí)例,并通過 connect()
方法連接到數(shù)據(jù)庫。在連接成功后,可以執(zhí)行數(shù)據(jù)庫操作,例如查詢、插入、更新或刪除文檔。
新建一個(gè)表試試
const userValue =new mongoose.Schema({ name: String, age: Number, email: String, password: String, phone: String, address: String, gender: String, dob: Date, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now } }); const User = mongoose.model('User', userValue);
在上面的代碼中,先聲明一個(gè)表的格式。使用new mongoose
的Schema
函數(shù),內(nèi)容為需要保存的字段。
再使用module.exports將表傳出去:
const mongoose = require('mongoose'); // MongoDB 連接字符串,包括數(shù)據(jù)庫地址和名稱 mongoose.connect('mongodb://localhost:27017/mydatabase') .then(() => { console.log('Connected to the database'); }) .catch((err) => { console.error('Failed to connect to the database:', err); }); const userValue =new mongoose.Schema({ name: String, age: Number, email: String, password: String, phone: String, address: String, gender: String, dob: Date, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now } }); const User = mongoose.model('User', userValue); module.exports = { User };
再使用index頁面接收一下:
const { User }= require('./db');
執(zhí)行數(shù)據(jù)庫操作:
在連接成功后,可以在回調(diào)函數(shù)中執(zhí)行數(shù)據(jù)庫操作。
// 在連接成功后執(zhí)行數(shù)據(jù)庫操作 client.connect(err => { if (err) { console.error('Failed to connect to the database:', err); return; } console.log('Connected successfully to the database'); const db = client.db(); // 查詢所有文檔 db.collection('mycollection').find().toArray((err, docs) => { if (err) { console.error('Error fetching documents:', err); return; } console.log('Documents:', docs); }); // 插入文檔 db.collection('mycollection').insertOne({ name: 'John', age: 30 }, (err, result) => { if (err) { console.error('Error inserting document:', err); return; } console.log('Document inserted:', result.insertedId); }); // 更新文檔 db.collection('mycollection').updateOne({ name: 'John' }, { $set: { age: 35 } }, (err, result) => { if (err) { console.error('Error updating document:', err); return; } console.log('Document updated:', result.modifiedCount); }); // 刪除文檔 db.collection('mycollection').deleteOne({ name: 'John' }, (err, result) => { if (err) { console.error('Error deleting document:', err); return; } console.log('Document deleted:', result.deletedCount); }); });
在上面的代碼中,db.collection()
方法用于獲取集合對象,然后可以使用該集合對象執(zhí)行查詢、插入、更新或刪除操作。
關(guān)閉數(shù)據(jù)庫連接:
在完成數(shù)據(jù)庫操作后,記得關(guān)閉數(shù)據(jù)庫連接,釋放資源。
// 關(guān)閉數(shù)據(jù)庫連接 client.close();
這樣,你的 Express 應(yīng)用程序就可以連接到 mongoose數(shù)據(jù)庫并執(zhí)行數(shù)據(jù)庫操作了。記得根據(jù)你的實(shí)際需求修改連接字符串和數(shù)據(jù)庫操作。
到此這篇關(guān)于Nodejs使用express連接數(shù)據(jù)庫mongoose的示例的文章就介紹到這了,更多相關(guān)express連接mongoose內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解nodejs搭建靜態(tài)服務(wù)器(實(shí)現(xiàn)命令行)
這篇文章主要介紹了深入理解nodejs搭建靜態(tài)服務(wù)器(實(shí)現(xiàn)命令行),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02vscode調(diào)試node.js的實(shí)現(xiàn)方法
這篇文章主要介紹了vscode調(diào)試node.js的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03NodeJS簡單實(shí)現(xiàn)WebSocket功能示例
這篇文章主要介紹了NodeJS簡單實(shí)現(xiàn)WebSocket功能,結(jié)合具體實(shí)例形式分析了nodejs實(shí)現(xiàn)WebSocket通信功能的客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下2018-02-02基于Node實(shí)現(xiàn)可以操作MySQL的接口
這篇文章主要介紹了用Node寫個(gè)可以操作MySQL的接口,以前也用Node寫過接口,但不涉及數(shù)據(jù)庫操作,而我們發(fā)現(xiàn),后端寫接口,基本都繞不開數(shù)據(jù)庫操作,感覺不寫一個(gè)能操作數(shù)據(jù)庫的接口,就不算真正意義上學(xué)會(huì)了寫接口,那我們今天就學(xué)習(xí)一下,如何寫一個(gè)可以操作數(shù)據(jù)庫的接口2024-05-05