ノードは、mongoDBに接続するためのサーバー環境を構築します

サーバーをセットアップする

  1. 新しいプロジェクトが開きます
  2. 初期化package.json端末入力をnpm init
  3. エントランスファイルserver.js
    私は著者に関するエントリー書類と書き込まれた情報を修正
    ここに画像の説明を挿入
  4. 現在のプロジェクトに必要なモジュールをインストールします npm install express
  5. Expressを導入してアプリをインスタンス化する
const express = require('express')
const app = express()
const port = process.env.PORT || 5000 
app.listen(port,()=>{
	console.log(`server running on port ${port}`)
})
  1. ルートを設定する
app.get('/',(req,res)=>{
	res.send('hello world')
})

入力端子は、node server.jsページのルートパスが表示されますhello world

  1. インストールはnodemon
    nodemon、各変更の役割は、面倒なステップを避けるために再起動する必要がありますされる
    sudo npm install nodemon -g
    ことによりnodemon server.js開始し

  2. 変態package.jsonscripts

// 前面通过 npm run start 线上打包启动
// 后面通过 npm run server 本地启动
"scripts":{
	"start":"node server.js",
	"server":"nodemon server.js"
}

以下は、サーバーが正常にポートを開始したことを証明するよう
ここに画像の説明を挿入
です
ここに画像の説明を挿入

データベースに接続する

mongoDBデータベースに接続するmongoDBデータベース
をインストールするhttps://blog.csdn.net/weixin_43883485/article/details/104534533
インストールを移動するmongoose
npm install mongoose

マングースの紹介

const mongoose = require("mongoose")

他にファイルのアドレス
新しいdb.js
におけるdb.jsアドレス名は、ローカルデータベースに書き込まれ
、このステップは、最初に作成する前にmongoデータベースtestDB
であればNavicat Premium、新たなビジュアルインターフェイスによって可能に
して、ダブルクリックしてtestDBデータベースをオープンし、それを
ここに画像の説明を挿入

ターミナルで新しいデータベースを作成しますtestDB
-mongodbを入力してサーバーを起動します
-mongoを入力してmongodbに接続します

show databases //显示当前所有数据库
use testDB //进入testDB数据库 如果没有testDB数据库 会创建testDB数据库
db //显示当前的数据库

次に、データベースのアドレスを入力して外部に公開します

module.exports = {
	mongoURI:"mongodb://127.0.0.1/testDB"
}

戻るserver.js紹介

const db = require("./db.js").mongoURI;
// 连接数据库
// mongoose.connect("mongodb://127.0.0.1/testDB",{useMongoClient:true}) 
mongoose.connect(db,{useMongoClient:true})
	.then(()=>console.log('mongoDB is connected'))
	.catch(err=>console.log(err))

端末が再起動しserver.js、データベース接続の成功を見ることができますプロンプトが表示され
、データベース接続がに成功したときに、2つの警告の出現を
ここに画像の説明を挿入
警告を解決します

DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
以前の接続方法が新しいバージョンに適用されない可能性があります。
次のよう変更してください

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.once('open',() => {
    console.log("mongoDB is connected")
});

起動は正常です。
ここに画像の説明を挿入
その後、インターフェースの作成を開始できます

41件のオリジナル記事を公開しました Likes2 1836を訪問します

おすすめ

転載: blog.csdn.net/weixin_43883485/article/details/105193327