温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-07-13 14:38:28 来源:亿速云 阅读:177 作者: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