What is a directing?



What is a Mongoose?






mongoosejs.com/
www.runoob.com/mongodb/mon…
http://www.runoob.com/mongodb/mongodb-linux-install.html






Schema, Model, Entity



Schema
Model






(1) Schema






Schema

const Articles = new Schema({   
  articleId: {type: String},   
  title: { type: String },   
  content: { type: String },   
  by: { type: String},   
  modifyOn: { type: Date, default: Date.now },  
}, { collection: 'articles' });
Copy the code



(2) Model












Schema
Model

mongoose.model('articles', Articles);
Copy the code



(3) Entity












Model
Entity

const article = new ArticlesModel(req.body); Model.create(req.body)Copy the code



2. Article management system






Mongoose
Express
Pug
Lodash






mongodb-pratice





cd mongoose-demo   


npm install   


npm start
Copy the code









  • Db: database related operation file, such as connect connect.js
  • Modules: Models, such as Artilces, that contain routes, methods, models, and so on
  • Views: template file
  • Public: static resource
  • Main. js: startup file



3. Project details



(1) Connect to the database


// db/connect.js const mongoose = require('mongoose'); exports.start = (success) => { mongoose.connect('mongodb://localhost/blog', { useMongoClient: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', () => { // we're connected! console.log('connected db: blog'); if (success) { success(); }}); };Copy the code

blog








// main.js  
const db = require('./db/connect');   
db.start();
Copy the code








mongoose.connect('mongodb://root:password@localhost/blog')
Copy the code






(2) Create a model








// modules/articles/articles.model.js const mongoose = require('mongoose'), Schema = mongoose.Schema; // Create Schema const Articles = new Schema({articleId: {type: String}, title: {type: String}, content: {type: String}) String }, by: { type: String}, modifyOn: { type: Date, default: Date.now }, }, { collection: 'articles' }); // Create Model mongoose. Model ('articles', articles);Copy the code








mongoose.model('articles', Articles, 'articles');
Copy the code









(3) Configure the API interface





In the above code, we have connected to the database and created an operational Model. Now we need to configure the API for us to call.

// modules/articles/articles/route.js  
const articleControllder = require('./articles.controller');   


module.exports = (app) => {   
  app.route('/api/article/add')   
    .post(articleControllder.add);       


  app.route('/api/article/find')   
    .get(articleControllder.get);    


  app.route('/api/article/remove')   
    .delete(articleControllder.remove);    


  app.route('/api/article/update')   
    .put(articleControllder.update);  
};
Copy the code






(4) Basic Operations (CRUD)








// modules/articles/articles.controller.js const mongoose = require('mongoose'); const ArticlesModel = mongoose.model('articles'); mongoose.Promise = global.Promise; const commonFunction = require('.. /common/common_function'); const _ = require('lodash'); exports.get = (req, res) => { const articleId = req.query['id']; Articlesmodel.findbyid (articleId, (err, result) => {if (err) {return res.status(400).send({message: 'find failed ', data: []}); } else { res.jsonp({ data: [result] }); }}); }; exports.add = (req, res) => { req.body['articleId'] = commonFunction.getRandom(); req.body['modifyOn'] = new Date(); req.body['by'] = 'TG'; const article = new ArticlesModel(req.body); Article. Save ((err) => {if (err) {return res.status(400). Send ({message: 'new failed ', data: []}); } else { res.jsonp({ data: [article] }); }}); }; exports.remove = (req, res) => { const id = req.query['id']; Articlesmodel.remove ({'_id': id}, (err) => {if (err) {return res.status(400).send({message: 'delete failed ', data: []}); } else { res.jsonp({status: 1}); }})}; exports.update = (req, res) => { const id = req.body['id']; Articlesmodel.findbyid (id, (err, result) => {if (err) {return res.status(400).send({message: 'update failed ', data: []}); } else { delete req.body['id']; const articles = _.extend(result, req.body); Articles. Save ((err, result) => {if (err) {return res.status(400). Send ({message: 'update failed ', data: []}); } else { res.jsonp({ data: [articles] }); }})}})};Copy the code

This is the basic CRUD operation.


You may be wondering why I didn’t export the Model, but I have loaded all published models in the boot file by default.

// main.js ... const loadModels = () => { files.forEach((v, k) => { if (/model.js$/.test(v)) { require(path.resolve(v)); }}); }; loadModels(); .Copy the code

You can get models anywhere by getting all the files in the Modules folder and then matching the model file with the suffix model.js:

const ArticlesModel = mongoose.model('articles');
Copy the code


You can also learn about common MongoDB statements in this article:


This is just a brief introduction to the basic connection and CRUD of Mongoose, and there are more contents for us to study in depth.


If you have any questions or comments, feel free to leave them in the comments section below!