Nodejs使用express連接數(shù)據(jù)庫mongoose的示例
前面需要準(zhǔn)備的內(nèi)容可看前面的文章:
簡(jiǎn)單用Nodejs + express 編寫接口
連接 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() 方法用于獲取集合對(duì)象,然后可以使用該集合對(duì)象執(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
NodeJS實(shí)現(xiàn)圖片上傳代碼(Express)
本篇文章主要介紹了NodeJS實(shí)現(xiàn)圖片上傳代碼(Express) ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06
使用Node.js創(chuàng)建一個(gè)簡(jiǎn)單的HTTP服務(wù)器的示例代碼
Node.js 是一種強(qiáng)大的 JavaScript 運(yùn)行環(huán)境,允許開發(fā)者在服務(wù)器端運(yùn)行 JavaScript 代碼,它以異步事件驅(qū)動(dòng)的方式處理大量連接,適合構(gòu)建高效的網(wǎng)絡(luò)應(yīng)用程序,在這篇文章中,我們將一起學(xué)習(xí)如何使用 Node.js 創(chuàng)建一個(gè)簡(jiǎn)單的 HTTP 服務(wù)器,并通過示例代碼幫你快速上手2025-02-02
Nodejs?Sequelize手冊(cè)學(xué)習(xí)快速入門到應(yīng)用
這篇文章主要為大家介紹了Nodejs?Sequelize手冊(cè)學(xué)習(xí)快速入門到應(yīng)用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
整理 node-sass 安裝失敗的原因及解決辦法(小結(jié))
這篇文章主要介紹了整理 node-sass 安裝失敗的原因及解決辦法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
koa-passport實(shí)現(xiàn)本地驗(yàn)證的方法示例
這篇文章主要介紹了koa-passport實(shí)現(xiàn)本地驗(yàn)證的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
npm使用淘寶鏡像安裝時(shí)報(bào)錯(cuò)的解決方案(npm淘寶鏡像到期盡快切換)
npm 淘寶鏡像到期了,盡快切換,本文給大家介紹了npm使用淘寶鏡像安裝時(shí)報(bào)錯(cuò)的解決方案,文中通過代碼示例和圖文講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-02-02
Node.js 與 Webpack 模塊化工程化入門指南教程
本文介紹了Node.js的基礎(chǔ)知識(shí),包括什么是Node.js、如何執(zhí)行代碼、fs和path模塊的使用方法,以及簡(jiǎn)易前端工程化實(shí)踐,隨后,文章講解了Web服務(wù)基礎(chǔ)、模塊化開發(fā)、npm包管理,以及使用Webpack進(jìn)行前端工程化和優(yōu)化,感興趣的朋友跟隨小編一起看看吧2026-03-03

