koa,express,node閫氱敤鏂规硶杩炴帴MongoDB
Posted Node鍓嶇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了koa,express,node閫氱敤鏂规硶杩炴帴MongoDB相关的知识,希望对你有一定的参考价值。
鍏充簬杩炴帴mysql锛岀湅杩欑瘒鏂囩珷
杩欎釜鏂规硶锛宯ode锛宔xpress锛宬oa杩炴帴MongoDB閮芥槸涓€鏍风殑鏂规硶锛屾垜浠埄鐢╩ongoose妯″潡鏉ヨ繛鎺?/p>
杩欓噷鍙槸绠€鍗曞垪涓€涓嬭繛鎺ongoDB鐨勭粨鏋勶紝鍏跺疄瑕佺湡姝f噦MongoDB锛岃繕闇€瑕佸緢澶氱煡璇嗙偣锛屾瘮濡侻ongoDB鐨勬暟鎹被鍨嬶紝杩樻湁涓€浜汚PI鎿嶄綔
绠€鍗曡涓€涓婱ongoDB鐨勭粨鏋?/p>
鍏朵粬鍐呭涓嬫锛屽垎浜紝浠婂ぉ鍏堣繛涓婐煒?/p>
娉ㄦ剰鎴戠殑鐗堟湰
杩欐槸鎴戠殑鐩綍
鎴戠殑瀹夎鐨勪緷璧栫増鏈細
"dependencies": {
"koa": "^2.6.2",
"mongoose": "^5.3.12",
}`
1.杩炴帴MongoDB
// db/db.js
const mongoose = require('mongoose')
const DB_URL = 'mongodb://localhost:27017/local'
mongoose.connect(DB_URL)
mongoose.connection.on('connected',function() {
console.log('Mongoose connection open to '+DB_URL);
});
/**
* 杩炴帴寮傚父 error 鏁版嵁搴撹繛鎺ラ敊璇?/span>
*/
mongoose.connection.on('error',function(err) {
console.log('Mongoose connection error: '+ err);
});
/**
* 杩炴帴鏂紑 disconnected 杩炴帴寮傚父鏂紑
*/
mongoose.connection.on('disconnected',function() {
console.log('Mongoose connection disconnected');
});
module.exports = mongoose
`
2.璁剧疆闇€瑕佹搷浣滅殑闆嗗悎
// db/index.js
const mongoose = require('./db')
const Schema = mongoose.Schema;
const ceshiSchema = new Schema({
title: String,
body: String,
date: Date
});
const MyModel = mongoose.model('ceshi', ceshiSchema);
class Mongodb {
constructor () {
}
// 鏌ヨ
query () {
return new Promise((resolve, reject) => {
MyModel.find({}, (err, res) => {
if(err) {
reject(err)
}
resolve(res)
})
})
}
// 淇濆瓨
save (obj) {
const m = new MyModel(obj)
return new Promise((resolve, reject)=> {
m.save((err, res) => {
if (err) {
reject(err)
}
resolve(res)
console.log(res)
})
})
}
}
module.exports = new Mongodb()
杩欓噷灏辩畝鍗曚妇渚嬩簡鏌ヨ鍜屼繚瀛樻柟娉曪紝杩樻槸鍏朵粬鏂规硶锛屽彲浠ュ叿浣撳幓鐪嬫枃妗?/p>
3.璁剧疆鏈嶅姟鍣?/h2>
// index.js
const Koa = require('koa')
const config = require('./config/default')
const ModelDb = require('./db')
const app = new Koa()
app.use(async (ctx) => {
let data = await ModelDb.query()
ctx.body = data
})
app.listen(config.port)
console.log(`listening on port ${config.port}`)
4.鍚姩鏈嶅姟鍣?/h2>
// index.js
const Koa = require('koa')
const config = require('./config/default')
const ModelDb = require('./db')
const app = new Koa()
app.use(async (ctx) => {
let data = await ModelDb.query()
ctx.body = data
})
app.listen(config.port)
console.log(`listening on port ${config.port}`)
鎵撳紑娴忚鍣紝灏卞彲浠ョ湅鐨勬煡璇㈠嚭鏉ョ殑缁撴灉
娉ㄦ剰锛氬墠鎻愬湪ceshi缁撳悎瑕佹湁鏂囨。锛屼篃灏辨槸瑕佹湁鏁版嵁
--
--
以上是关于koa,express,node閫氱敤鏂规硶杩炴帴MongoDB的主要内容,如果未能解决你的问题,请参考以下文章
uiautomatorviewer杩炴帴鏈哄櫒鐐瑰嚮鎶ラ敊Unexpected error while obtaining UI hierarchy