MongoDB是由C++编写的基于分布式文件储存的数据库,尤其是在Node.js中使用广泛。
具体怎么下载安装大家可以参考这个 Link 本章节不做过多解释
接下来命令行下运行 MongoDB shell
C:\mongodb\bin\mongo.exe
或者我们可以使用官方推荐的MongoDB Compass, 亲测比Robo 3T好用且免费
image.png接下来我们重构我们的目录结构
创建db文件夹 接下来在db文件夹中创建config schemas models
config
config.js
module.exports = {
url_string:
'mongodb://localhost:20710/admin'
};
mongoose.js
const mongoose = require('mongoose');
const config = require('./config');
module.exports = () => {
mongoose.connect(config.url_string, { useNewUrlParser: true }); //connect if locahost please fill mongodb://localhost:20710/admin
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connect err:'));
db.once('open', callback => {
console.log('connect MongoDB suc');
});
return db;
};
models
exampleModel.js
const mongoose = require('mongoose');
const ExampleSchema = require('../schemas/exampleSchema');
//创建model,这个地方的user对应mongodb数据库中admin的conllection。
const Example = mongoose.model('word', ExampleSchema);
module.exports = Example;
shcemas
exampleSchema.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//创建Schema
const ExampleSchema = new Schema({
word: String,
definition: String
});
module.exports = ExampleSchema;
接下来我们重新创建个路由custview
custview.js
const express = require('express');
const router = express.Router();
const Example = require('../db/models/exampleModel'); // 引入模型
router.get('/list', (req, res) => {
Example.find({}, (err, data) => {
if (err) next(err);
res.json(data);
});
});
module.exports = router;
在app.js中链接db
const mongoose = require('./db/config/mongoose');
const db = mongoose();
启动server在浏览器中调用
image.png
最终我们的目录结构如下所示
├── app.js
├── bin
| └── www
├── db
| ├── config
| | ├── config.js
| | └── mongoose.js
| ├── models
| | └── exampleModel.js
| └── schemas
| └── exampleSchema.js
├── package-lock.json
├── package.json
├── public
| ├── images
| ├── javascripts
| └── stylesheets
| └── style.css
├── routes
| ├── custview.js
| ├── index.js
| └── users.js
├── views
| ├── error.jade
| ├── index.jade
| └── layout.jade
└── yarn.lock
我们的代码我也上传到了github欢迎大家查看
网友评论