mongoose鏈接mongodb分爲三步node
首先建立Schema,由Schema生成Model,再根據Model生成Entitymongodb
下面是詳細代碼:npm
先建立文件夾,執行mongoose
npm init && npm install mongoose --save
而後新建index.js文件,開始編碼:ui
const mongoose = require('mongoose'); let url = "mongodb://test:test@119.23.243.252:27017/test"; mongoose.connect(url, {useNewUrlParser: true}); var mySchema = new mongoose.Schema({ name: String, age: Number, sex: String, time: String }); var myModel = mongoose.model('user', mySchema); var entity = new myModel({ name: 'zhangsan', age: 21, sex: 'boy', time: (new Date()).toLocaleString() }); entity.save((err, doc)=>{ if(err){ console.log(err); }else{ console.log(doc); } });
執行node index.js編碼
插入數據成功,進入mongodb中查看url
沒有問題,可是這裏有一個注意的地方,建立Model時給的collection名稱是user,在mongodb中查看時變成了users,spa
會自動在後面添加一個scode