欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Nodejs使用express連接數(shù)據(jù)庫(kù)mongoose的示例

 更新時(shí)間:2024年06月14日 10:10:06   作者:奶糖 肥晨  
數(shù)據(jù)庫(kù)并進(jìn)行操作通常需要使用第三方庫(kù),其中最流行的是mongoose,本文主要介紹了Nodejs使用express連接數(shù)據(jù)庫(kù)mongoose的示例,具有一定的參考價(jià)值,感興趣的可以了解一下

前面需要準(zhǔn)備的內(nèi)容可看前面的文章:

Express框架搭建項(xiàng)目 node.js

簡(jiǎn)單用Nodejs + express 編寫(xiě)接口

連接 mongoose數(shù)據(jù)庫(kù)需要使用 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ù)庫(kù)連接:

創(chuàng)建一個(gè) mongoose客戶(hù)端,并通過(guò)客戶(hù)端連接到 mongoose數(shù)據(jù)庫(kù)。

const mongoose = require('mongoose');

// mongoose連接字符串,包括數(shù)據(jù)庫(kù)地址和名稱(chēng)
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ù)庫(kù)的連接字符串,其中包括數(shù)據(jù)庫(kù)地址和名稱(chēng)。然后,創(chuàng)建一個(gè)新的 mongoose 實(shí)例,并通過(guò) connect() 方法連接到數(shù)據(jù)庫(kù)。在連接成功后,可以執(zhí)行數(shù)據(jù)庫(kù)操作,例如查詢(xún)、插入、更新或刪除文檔。

新建一個(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 mongooseSchema函數(shù),內(nèi)容為需要保存的字段。

在這里插入圖片描述

再使用module.exports將表傳出去:

const mongoose = require('mongoose');

// MongoDB 連接字符串,包括數(shù)據(jù)庫(kù)地址和名稱(chēng)
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頁(yè)面接收一下:

const { User }= require('./db');

在這里插入圖片描述

執(zhí)行數(shù)據(jù)庫(kù)操作:

在連接成功后,可以在回調(diào)函數(shù)中執(zhí)行數(shù)據(jù)庫(kù)操作。

// 在連接成功后執(zhí)行數(shù)據(jù)庫(kù)操作
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();

  // 查詢(xún)所有文檔
  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í)行查詢(xún)、插入、更新或刪除操作。

關(guān)閉數(shù)據(jù)庫(kù)連接:

在完成數(shù)據(jù)庫(kù)操作后,記得關(guān)閉數(shù)據(jù)庫(kù)連接,釋放資源。

// 關(guān)閉數(shù)據(jù)庫(kù)連接
client.close();

這樣,你的 Express 應(yīng)用程序就可以連接到 mongoose數(shù)據(jù)庫(kù)并執(zhí)行數(shù)據(jù)庫(kù)操作了。記得根據(jù)你的實(shí)際需求修改連接字符串和數(shù)據(jù)庫(kù)操作。

到此這篇關(guān)于Nodejs使用express連接數(shù)據(jù)庫(kù)mongoose的示例的文章就介紹到這了,更多相關(guān)express連接mongoose內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何優(yōu)雅地在Node應(yīng)用中進(jìn)行錯(cuò)誤異常處理

    如何優(yōu)雅地在Node應(yīng)用中進(jìn)行錯(cuò)誤異常處理

    這篇文章主要介紹了如何優(yōu)雅地在Node應(yīng)用中進(jìn)行錯(cuò)誤處理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Node.js簡(jiǎn)單入門(mén)前傳

    Node.js簡(jiǎn)單入門(mén)前傳

    Node.js 是一個(gè)基于Chrome JavaScript 運(yùn)行時(shí)建立的一個(gè)平臺(tái)。接下來(lái)通過(guò)本文給大家分享node.js 入門(mén)前傳,感興趣的朋友一起看看吧
    2017-08-08
  • Node發(fā)出HTTP POST請(qǐng)求的方法實(shí)例小結(jié)

    Node發(fā)出HTTP POST請(qǐng)求的方法實(shí)例小結(jié)

    這篇文章主要介紹了Node發(fā)出HTTP POST請(qǐng)求的方法,結(jié)合實(shí)例形式總結(jié)分析了三種常用的post請(qǐng)求操作方法,以及相關(guān)庫(kù)操作注意事項(xiàng),需要的朋友可以參考下
    2023-05-05
  • Node.js JSON模塊用法實(shí)例分析

    Node.js JSON模塊用法實(shí)例分析

    這篇文章主要介紹了Node.js JSON模塊用法,結(jié)合實(shí)例形式分析了node.js json模塊的基本語(yǔ)法,以及使用json模塊進(jìn)行json格式數(shù)據(jù)解析的相關(guān)操作技巧,需要的朋友可以參考下
    2019-01-01
  • Node koa服務(wù)器實(shí)現(xiàn)獲取客戶(hù)端ip

    Node koa服務(wù)器實(shí)現(xiàn)獲取客戶(hù)端ip

    這篇文章主要為大家詳細(xì)介紹了Node koa服務(wù)器實(shí)現(xiàn)獲取客戶(hù)端ip的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解下
    2025-02-02
  • module.exports和exports使用誤區(qū)案例分析

    module.exports和exports使用誤區(qū)案例分析

    module.exports和exports使用誤區(qū),使用require()模塊時(shí),得到的永遠(yuǎn)都是module.exports指向的對(duì)象
    2023-04-04
  • 從零學(xué)習(xí)node.js之express入門(mén)(六)

    從零學(xué)習(xí)node.js之express入門(mén)(六)

    相信大家都知道Express是一個(gè)簡(jiǎn)潔而靈活的 node.js Web應(yīng)用框架, 提供了一系列強(qiáng)大特性幫助你創(chuàng)建各種 Web 應(yīng)用,和豐富的 HTTP 工具。下面這篇文章主要介紹了node.js中express的入門(mén)知識(shí),需要的朋友可以參考下。
    2017-02-02
  • 詳解node字體壓縮插件font-spider的用法

    詳解node字體壓縮插件font-spider的用法

    在本篇文章中給大家詳細(xì)講述了node字體壓縮插件font-spider的用法的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友參考下。
    2018-09-09
  • Node.js調(diào)用java之node-java問(wèn)題

    Node.js調(diào)用java之node-java問(wèn)題

    這篇文章主要介紹了Node.js調(diào)用java之node-java問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Nodejs實(shí)現(xiàn)多文件夾文件同步

    Nodejs實(shí)現(xiàn)多文件夾文件同步

    這篇文章主要為大家介紹了Nodejs實(shí)現(xiàn)多文件夾文件同步,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-10-10

最新評(píng)論