Mongoose is introduced
Mongoose. Js Chinese website
In the face of this dilemma, writing MongoDB validation, transformation, and business logic can be cumbersome. So Mongoose was invented
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() = > console.log('meow'));
Copy the code
Mongoose provides a straightforward, Scheme-based structure for defining your data model. It has built-in data validation, query build, business logic hooks, and more, right out of the box
Mongoose is an elegant NodeJS Object Document Module. It designs non-relational database through the idea of relational database. It is based on mongodb driver to simplify operation
Mogoose does a lot of packaging for mongodb
- Scheme corresponds to tables
- Module corresponds to a database collection
- Documents Document object
Initialization & Installation
npm init -y
npm i express mongodb mongoose -s
Copy the code
use
// Import modules
const mongoose = require('mongoose')
// Connect, configure the database, return a pending connection
mongoose.connect('mongo: / / 192.168.31.107:27017', {
user: 'maxuan'.pass: '601109'.dbName: 'blog'.autoIndex: false.useNewUrlParser: true
})
// Get the database object
const db = mongoose.connection
// Warning of connection failure
db.on('error'.console.error.bind(console.'connection error:'))
// The connection succeeded
db.once('open'.async() = > {// we are connected!
// Define a Schema = table
const blogSchema = new mongoose.Schema({
title: String.author: String.body: String.comments: [{body: String.date: Date}].date: {
type: Date.default: Date.now
},
hidden: Boolean.meta: {
votes: Number.favs: Number}})// Compile Schema into a model
const blogs = mongoose.model('blogs', blogSchema)
// Operate on a collection of databases through a model
})
Copy the code
After configuring connection, set the database name. If you do not set this parameter, the test database will be automatically generated
The useUnifiedTopology: True configuration is supported when connecting to the latest version of mongodb
Mongoose doesn’t have an insertOne() method, which inserts a piece of data and passes an object into the array
The names of the created collections are converted to all lowercase, if plural names remain unchanged, and if singular names are automatically added as s or es
Run server.js, print data insert successfully, refresh database, set creation complete, data insert successfully
Db.once (‘open’,async ()=> {}
The Query API documentation
Mongoose 5.0 英 文 documentation – Query
increase
await blogs.insertMany([
{
title: 'Vue'.author: 'youyuxi'.body: 'Vue is a lightweight and efficient front-end framework '.comments: [{body: 'You're right.'.date: new Date()}].hidden: true.meta: {
votes: 10.favs: 200}}, {title: 'React'.author: 'facebook'.body: 'React is a much better front-end framework '.comments: [{body: 'That's not quite right.'.date: new Date()}].hidden: false.meta: {
votes: 20.favs: 400}}])console.log('Data inserted successfully');
Copy the code
The query
let r = await blogs.find({author: 'youyuxi'})
console.log(r)
/* [ { meta: { votes: 10, favs: 200 }, _id: new ObjectId("616c477f330f6921c48c5baf"), title: 'Vue', author: Comments: [[Object]], Hidden: true, Date: 2021-10-17t15:55:43.727z, __v: 0}] * /
Copy the code
If the ID obtained here is new ObjectId, the front-end needs to convert it into a string through r[0].id.tohexString () and return the string to the server for query or other operations
Call mongoose’s query and() API method
let r = await blogs.find().and([
{
author: 'facebook'
},
{
title: 'Vue'}])console.log(r);
Copy the code
update
Update and return the updated status
r = await blogs.where({author: 'youyuxi'}).updateOne({title: 'Vue.js'})
console.log(r)
/* { acknowledged: true, modifiedCount: 1, upsertedId: null, upsertedCount: 0, matchedCount: 1 } */
Copy the code
Update and return the update result
r = await blogs.findOneAndUpdate({author: 'youyuxi'}, {$set: {title: 'Vue.js'}})
console.log(r);
/* { meta: { votes: 10, favs: 200 }, _id: new ObjectId("616c4898ab1f6d1fc43fced6"), title: 'Vue.js', author: 'Youyuxi ', body: 'Vue is a lightweight and efficient front-end framework ', comments: [{body:' right ', Date: 2021-10-17t16:00:24.138z, _id: New ObjectId(" 616C4898AB1F6d1FC43fced7 ")}], Hidden: true, Date: 2021-10-17T16:00:24.148z, __v: 0} */
Copy the code
delete
r = await blogs.deleteOne({author: 'youyuxi'})
console.log(r);
// { deletedCount: 1 }
Copy the code
Define methods
Instance methods
Methods defined on Schema objects that need to be called via model(‘blogs’) after this must be defined before compiling the Blogs model and cannot use arrow functions because this points to them
To use this method, new a model instance, configure the corresponding parameters in the instance method find, and then call the method on the model instance
blogSchema.methods.findAuthor = function() {
// Returns a query condition for the model
return this.model('blogs').find({author: this.author}).exec()
}
// Compile Schema into a model
const blogs = mongoose.model('blogs', blogSchema)
// Get the model instance and configure the query parameters
let b = new blogs({author: 'youyuxi'})
// Call the instance method to return the result
r = await b.findAuthor()
console.log(r);
/* [ { meta: { votes: 10, favs: 200 }, _id: new ObjectId("616c4898ab1f6d1fc43fced6"), title: 'Vue', author: Comments: [[Object]], Hidden: true, Date: 2021-10-17t16:00:24.148z, __v: 0}] * /
Copy the code
__v: 0 – Used as a query condition when saving documents, so that the data is not modified by other processes between “fetch data” and “save data”, resulting in conflicts in the final modification
We’re using find, and we can get multiple results so we’re returning an array. If the goal is to return a unique result, use findOne
The exec(callback) method after the instance method is defined, which calls the callback function when data is retrieved. This method can be used
A static method
Methods defined on models, which call static methods directly on model objects and pass parameters back to R, must be defined before compiling the Blogs model, and cannot be used with arrow functions because this points to
blogSchema.statics.findTitle = function(title) {
return this.findOne({title: title}).exec()
}
const blogs = mongoose.model('blogs', blogSchema)
r = await blogs.findTitle('Vue')
console.log(r);
Copy the code
Virtual properties
Virtual properties are handlers used on the returned result r object, equivalent to Vue’s computed properties, that process the returned result
blogSchema.virtual('getContent').get(function() {
return `The ${this.author}Released a video calledThe ${this.title}Front-end framework '
})
// Compile Schema into a model
const blogs = mongoose.model('blogs', blogSchema)
r = await blogs.findTitle('Vue')
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- left left left left left left left down down down down down down
console.log(r.getContent)
// Youyuxi released a front-end framework called Vue
Copy the code