启动mongoDB
命令
在 C:MangoDB\data\bin 目录(安装mongodb的目录)下执行操作
1
| mongod --dbpath C:\MangoDB\data\db
|
MangoDB默认端口27017
配置连接数据库
1 2 3
| var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/studyFirst', { useNewUrlParser: true })
|
表名默认+s
1 2 3 4 5 6 7 8 9
| const Models = { Blog: mongoose.model('Blog', new mongoose.Schema({ title: String }, { collection: 'Blogs' })), Tag: mongoose.model('Tag', new mongoose.Schema({ title: String })) }
|
router
接口举例
1 2 3 4 5 6 7 8 9
| app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html') })
// await 异步操作 async 表明异步函数 成对出现(有await必须async) router.get('/getOne', async (req, res, next) => { res.send(await Blog.find().skip(1).limit(1)) })
|
post注意
1 2 3 4 5 6 7 8
| const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json())
app.use(bodyParser.urlencoded({limit: '50mb', extended: true})) app.use(bodyParser.json({limit: '50mb'}))
|
跨域
1
| app.use(require('cors')())
|
request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const request = require('request')
request.get({url: Url}, (err, httpResponse, body) => { if (err) { return console.error('failed:', err) } console.log(body) })
request.post({url: Url, form: req.body}, (err, httpResponse, body) => { if (err) { return console.error('failed:', err) } console.log(body) })
|