// 安装express
npm install express--save
// server.js
const express = require('express')
// 新建app
const app = express()
app.get('/', function(req, res){
res.send('Hello world
')
})
app.listen(3000, function(){
console.log('Node app start at port 3000')
})
// 此时在server.js目录下命令行运行node server.js
// http://localhost:3000渲染出Hello world
// 修改渲染信息
// server.js
const express = require('express')
// 新建app
const app = express()
app.get('/', function(req, res){
res.send('Hello world
')
})
app.get('/data', function(req, res){
res.json({user: 'Edison', age: 20})
})
app.listen(3000, function(){
console.log('Node app start at port 3000')
})
// http://localhost:3000/data 取不到对象
此时需要在命令行重新运行node server.js,为了不重复操作,安装nodemon:
// 安装nodemon
npm install nodemon--save
在server.js文件同级目录命令行中:nodemon server.js,此后修改数据自动更新localhost:3000
F:\>cd F:\workTool\mongodb\bin
F:\workTool\mongodb\bin>mongo
MongoDB shell version v4.0.5
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("df58d557-2e9f-4508-a1db-98cdfb83847d") }
MongoDB server version: 4.0.5
Server has startup warnings:
2019-01-21T09:05:01.710+0800 I CONTROL [initandlisten]
2019-01-21T09:05:01.710+0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-01-21T09:05:01.710+0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-01-21T09:05:01.710+0800 I CONTROL [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
const DB_URL = 'mongodb://127.0.0.1:27017/Edison'
mongoose.connect(DB_URL)
mongoose.connection.on('connected', function(){
console.log('mongo connect success')
})
建表,类似于mysql,mongo里有文档、字段的概念 const User = mongoose.model('user', new mongoose.Schema({
user: {type: String, require: true},
age: {type: Number, require: true}
}))
新增数据: // 新增数据
User.create({
user: 'Edison',
age: 20
}, function(err, doc){
if (!err) {
console.log(doc)
} else {
console.log(err)
}
})
查找数据: app.get('/data', function(req, res){
User.find({}, function(err, doc){
res.json(doc)
})
})
// 只查一条
app.get('/data', function(req, res){
User.findOne({}, function(err, doc){
res.json(doc)
})
})
删除数据: User.remove({age: 20}, function(err, doc){
if (!err) {
console.log(doc)
} else {
console.log(err)
}
})
修改数据: // 更新数据
User.update({'user': 'Edison'}, {'$set': {age: 26}}, function(err, doc){
console.log(doc)
})