Use of mongodb and Mongoose
- The course introduction can be found here: juejin.cn/post/684490…
- Github address: github.com/hellozhangr…
mongodb
Mongodb is a typical non-relational database. Its background and advantages and disadvantages are not described here. We will directly talk about the practical operation or the most likely to use part.
Mongodb common commands
mongod --config /opt/mongodb/mongod.conf
Start the Mongod service.- If you want to start in the background, modify mongod. Conf, add fork=true, and start again.
- To turn off the mongod service running in the background, look at all the mongod services running in the background
lsof -i
, find the MONgod PID,kill yourpid
mongo
Enter the Mongo environmentshow dbs
View all databasesuse test
Enter the test databasedb.createCollection('user')
To create auser
A collection of- Here is a brief introduction to the concept of set, mongo is a non-relational database, there is no concept of tables, and the corresponding table is set. Of course, a set is not a table, which is very different from a table. Without the column structure of a table, a set can simply be regarded as a list, and a list will put objects in it. Notice how this looks like a JSON data format.
db.user.insert({name: 'zhangsan', age: 21, sex: 'male'})
Inserts a piece of data into the collectiondb.user.find()
View all the data in the collection Userdb.user.find().pretty()
Display data in a nice formatdb.user.find({name: 'zhangsan'})
The first parameter to find is the WHERE selection condition, which displays the entire data whose name=’zhangsan’db.user.find({name: 'zhangsan'}, {name: 1})
The first argument to find is to specify what to display, and to display the qualified name, 1 for display, 0 for not display.
Use the mongoose
Mongoose is a nodeJS tool library for manipulating mongodb with NodeJS
1. Connect the mongodb database using Mongoose
const mongoose = require('mongoose');
// Create a connection and listen for events that will be triggered as the case may be when the connect operation is executed.
mongoose.connection
.on('error'.function (err) {
// Triggered when the database connection fails
console.log('connect error: ', err);
})
.on('disconnected'.function () {
// When the database is disconnected, the logic to disconnect and reconnect can be placed here.
})
.once('open'.function () {
// Listen is triggered when the database connection is successful.
});
// Start the Mongod service on 127.0.0.1 by default, so the following path is localhost
// test is the name of the database, connect if it exists, and create if it does not
mongoose.connect('mongodb://localhost/test', {
useNewUrlParser: true.useUnifiedTopology: true
});
Copy the code
2. The Schema and the Model
Schema and Model are very important concepts in Mongoose. Model corresponds to the collection in mongodb, while Schema corresponds to the structure of the collection, that is, the combination of the fields, the type of the fields, whether it is required, whether there is a default value, etc.
const UserSchema = mongoose.Schema({
name: String.age: Number.sex: Boolean
});
// static method of Schema
UserSchema.statics.findUserByAge = function (age) {
FindUserByAge (21).then((res) => {})
// We can also return the call function in find with the second argument
return this.find({'age': age});
}
// Schema instance method
UserSchema.methods.findUserByName = function(name) {
return this.model('User').find({ name: name });
};
// Create a Model. The third parameter specifies the name of the collection in mongodb.
const User = mongoose.model('User', UserSchema, 'user');
// Create a data item
// 1
User.create({name: 'zhangsan'.age: 27.sex: true}, function(err, info) {
console.log(info);
});
// 2. Create a new object and add data to the database
// Again, mongoose supports promise by default. Then or callback functions can be used
var person = new User({name: 'lisi'.age: 20.sex: false});
person.save().then(res= > {
console.log(res);
})
// Call static methods defined in the Schema, which can be invoked directly by User
User.findUserByAge(21);
// Call the instance method method defined in the Schema, instantiate first and then call
const user = new User();
user.findUserByName('zhangsan');
// Delete the data that meets the condition
User.deleteOne({name: 'lisi'}).then();
// Delete all data that matches the conditions
User.deleteMany({age: 20}).then();
// Note: the remove() method is deprecated!
Copy the code
Finally, attached is the API document of Mongoose, and other usage methods are not listed in one list:
www.mongoosejs.net/docs/api.ht…
TODO
The above is what has been used in the current project and may be further expanded in the future:
- The docker and mongo
- Automatic DISASTER recovery of mongodb replication sets