mongoose is more convenient to use
Using mongodb data driver to write an error log
For more information on the official data-driven mongodb of node
asset assertion is not used here
import mongodb from 'mongodb' const MongoClient = mongodb.MongoClient const url = 'mongodb://localhost:27017/edu' export default (errLog, req, res, next) => { // 1. Record the error log to the database for troubleshooting // 2. Send a response to the user and give some friendly prompt information // {error Name: error message: error stack: error time} // 1. Open connection MongoClient.connect(url, (err, db) => { db .collection('error_logs') .insertOne({ name: errLog.name, message: errLog.message, stack: errLog.stack, time: new Date() }, (err, result) => { res.json({ err_code: 500, message: errLog.message }) }) // 3. Close the connection db.close() }) }
storage structure
- There can be a database service instance on a computer
- A data service instance can have multiple databases
- There can be multiple collections in a database
- Set is divided according to the business type of data
- For example, user data, product information data, advertising information data...
- Store data by category
- Collections are like arrays in MongoDB
- There can be multiple documents in a collection
- Document is a JSON like data object in MongoDB
- Document objects are dynamic and can be generated at will
- In order to facilitate management, it is better to keep the document structure uniform (data integrity) for the data stored in a collection
{ collection1: [ { a: { age: 18, name: '', lsit: [], is: true } }, { Document 2 }, { Document 3 } ], collection2: [ ], collection3: [ ], collection4: [ ], }
Using mongoose
const mongoose = require('mongoose') mongoose.connect('mongodb://localhost/test') // 1. Create a model architecture, design data structure and constraints const studentSchema = mongoose.Schema({ name: String, age: Number }) // 2. Publish the architecture as a model through mongoose.model() (the model can be considered as a constructor) // The first argument is to give your set a name, preferably Pascal // For example, if your collection name is persons, it will be named Person here, but in the end mongoose will automatically help you turn Person into persons // The second parameter is to pass a model architecture const Student = mongoose.model('Student', studentSchema) // 3. Operate your database through the operation model // Save instance data object const s1 = new Student({ name: 'Mike', age: 23 }) s1.save((err, result) => { if (err) { throw err } console.log(result) }) //query Student.find((err, docs) => { if (err) { throw err } console.log(docs) }) Student.find({ name: 'Mike' },(err, docs) => { if (err) { throw err } console.log(docs) })