ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 在Ubuntu 19.10中使用mongoose来连接mongoDB

在Ubuntu 19.10中使用mongoose来连接mongoDB

原创 Linux操作系统 作者:iherb中文 时间:2020-05-17 20:31:09 0 删除 编辑

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 } ]

 

完成。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31380193/viewspace-2692614/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2016-08-01

  • 博文量
    15
  • 访问量
    23702