新聞中心
本篇文章為大家展示了在Ubuntu 19.10中怎么利用mongoose連接MongoDB,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
站在用戶的角度思考問題,與客戶深入溝通,找到普洱網(wǎng)站設(shè)計與普洱網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設(shè)計與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網(wǎng)站設(shè)計、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、空間域名、網(wǎng)頁空間、企業(yè)郵箱。業(yè)務(wù)覆蓋普洱地區(qū)。
Mongoose是一個建立在MongoDB驅(qū)動之上的ODM(對象數(shù)據(jù)建模)庫。它允許在NodeJS環(huán)境中與MongoDB進行簡潔的交互和簡單的對象建模。
在開始之前,建議:
設(shè)置具有sudo特權(quán)的非根用戶。
驗證您的服務(wù)器是最新的。
確保安裝了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
添加最新的穩(wěn)定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項目
創(chuàng)建項目根目錄。
$ cd ~
$ mkdir mongooseProject && cd mongooseProject
初始化一個NodeJS開發(fā)環(huán)境,自動生成一個package.json:
$ npm init
根據(jù)你的項目回答簡短的問題。例如,如果您在每個問題上按return接受默認值,npm init進程會響應(yīng):
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:定義一個模型
在項目根目錄中創(chuàng)建一個名為Models的文件夾,并將cd放入其中:
$ cd ~/mongooseProject
$ mkdir Models && cd Models
創(chuàng)建connectDB.js。該文件將包含MongoDB服務(wù)器所需的連接邏輯。
$ nano connectDB.js
將以下內(nèi)容粘貼到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
});
}
創(chuàng)建Users.js。這個文件將包含數(shù)據(jù)庫集合用戶的模型。
$ nano Users.js
將以下內(nèi)容粘貼到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
在項目的根目錄中創(chuàng)建insertUser.js。
$ cd ~/mongooseProject
$ nano insertUser.js
將以下內(nèi)容粘貼到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讀取文檔
在項目的根目錄中創(chuàng)建readUsers.js。
$ cd ~/mongooseProject
$ nano readUsers.js
將以下內(nèi)容粘貼到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 輸出是一個對象數(shù)組。
$ node readUsers.js
Successful connection with database: mongodb://localhost:27017/mongoose
[ { _id: ************************,
name: 'John Doe',
age: 18,
role: 'Example User',
__v: 0 } ]
完成。
上述內(nèi)容就是在Ubuntu 19.10中怎么利用mongoose連接mongoDB,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享題目:在Ubuntu19.10中怎么利用mongoose連接mongoDB
文章位置:http://ef60e0e.cn/article/joejgh.html