溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

在Ubuntu 19.10中怎么利用mongoose連接mongoDB

發布時間:2021-07-13 14:38:28 來源:億速云 閱讀:203 作者:Leah 欄目:建站服務器

本篇文章為大家展示了在Ubuntu 19.10中怎么利用mongoose連接mongoDB,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

Mongoose是一個建立在MongoDB驅動之上的ODM(對象數據建模)庫。它允許在NodeJS環境中與MongoDB進行簡潔的交互和簡單的對象建模。

在開始之前,建議:

設置具有sudo特權的非根用戶。

驗證您的服務器是最新的。

確保安裝了build-essential。如果不是,安裝使用:

$ sudo apt install build-essential

步驟1:MongoDB

安裝MongoDB

$ sudo apt install mongodb

檢查安裝是否正確。在輸出中查找“active (running)”。

$ sudo systemctl status mongodb
Active: active (running)

步驟2:NodeJS和NPM

添加最新的穩定NodeJS庫。

$ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -

安裝NodeJS

$ sudo apt install nodejs

檢查NodeJS和NPM是否安裝正確。

$ node -v && npm -v
v12.x.x
6.x.x

步驟3:初始化Mongoose項目

創建項目根目錄。

$ cd ~
$ mkdir mongooseProject && cd mongooseProject

初始化一個NodeJS開發環境,自動生成一個package.json:

$ npm init

根據你的項目回答簡短的問題。例如,如果您在每個問題上按return接受默認值,npm init進程會響應:

About to write to /root/mongooseProject/package.json:
 
{
"name": "mongooseproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}

使用npm在項目根目錄中安裝所需的包:

$ npm install --save mongoose

步驟4:定義一個模型

在項目根目錄中創建一個名為Models的文件夾,并將cd放入其中:

$ cd ~/mongooseProject
$ mkdir Models && cd Models

創建connectDB.js。該文件將包含MongoDB服務器所需的連接邏輯。

$ nano connectDB.js

將以下內容粘貼到connectDB.js中。

const mongoose = require('mongoose'); // Import mongoose library
 
module.exports = function(uri) {
    mongoose.connect(uri, {  //attempt to connect to database
        useNewUrlParser: true, // Recommended, insures support for future MongoDB drivers
        useUnifiedTopology: true // Recommended, uses new MongoDB topology engine
    }).catch(error => console.log(error)) // Error handling
 
 
    mongoose.connection.on('connected', function () { // On connection
        console.log('Successful connection with database: ' + uri); // Callback for successful connection
    });
}

創建Users.js。這個文件將包含數據庫集合用戶的模型。

$ nano Users.js

將以下內容粘貼到Users.js中。這為用戶定義了一個基本模式。

const mongoose = require("mongoose"); // Import mongoose library
const Schema = mongoose.Schema // Define Schema method
 
// Schema
var UsersSchema = new Schema({ // Create Schema
    name: String, // Name of user
    age: Number, // Age of user
    role: String // Role of user
})
 
// Model
var Users = mongoose.model("Users", UsersSchema) // Create collection model from schema
module.exports = Users // export model

步驟5:將文檔插入MongoDB

在項目的根目錄中創建insertUser.js。

$ cd ~/mongooseProject
$ nano insertUser.js

將以下內容粘貼到insertUser.js文件中。該文件將文檔插入到用戶集合中。

//Library
const mongoose = require("mongoose")
 
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
 
// Models
const Users = require("./Models/Users")
 
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
 
var insertedUser = new Users({ // Create new document
    name: "John Doe",
    age: 18,
    role: "Example User"
})
 
insertedUser.save(err => { // save document inside Users collection
    if(err) throw err // error handling
    console.log("Document inserted!")
    mongoose.disconnect() // disconnect connection from database once document is saved
})

運行insertUser.js

$ node insertUser.js
Successful connection with database: mongodb://localhost:27017/mongoose
Document inserted!

步驟6:從MongoDB讀取文檔

在項目的根目錄中創建readUsers.js。

$ cd ~/mongooseProject
$ nano readUsers.js

將以下內容粘貼到readUsers.js中。該文件讀取用戶集合中的文檔。

//Library
const mongoose = require("mongoose")
 
// Database connection
const connectDB = require("./Models/connectDB")
var database = "mongoose" // Database name
 
// Models
const Users = require("./Models/Users")
 
// Connect to database
connectDB("mongodb://localhost:27017/"+database)
 
Users.find({}, (err, users)=>{ //find and return all documents inside Users collection
    if(err) throw err // error handling
    console.log(users)
    mongoose.disconnect()
})

運行readUsers.js 輸出是一個對象數組。

$ node readUsers.js
Successful connection with database: mongodb://localhost:27017/mongoose
[ { _id: ************************,
    name: 'John Doe',
    age: 18,
    role: 'Example User',
    __v: 0 } ]

完成。

上述內容就是在Ubuntu 19.10中怎么利用mongoose連接mongoDB,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女