Use of mongodb and mongoose
* This paper is the third in this series, you can go directly to github want to see more projects: https://github.com/hellozhangran/happy-egg-server
more of the description can be seen: HTTPS: //www.cnblogs. com / zhangran / p / 11963616.html
mongodb
mongodb is a typical non-relational database, presentation about its background, strengths and weaknesses not go into details here, we speak directly to practical operation or most likely part used.
mongodb common commands
mongod --config /opt/mongodb/mongod.conf
Start mongod service.- If you want to start in the background, you need to modify mongod.conf, add fork = true, then start.
- Mongod want to turn off the service running in the background, first check all the services running in the background
lsof -i
, find the pid number mongod,kill yourpid
mongo
Mongo into the environmentshow dbs
View all databasesuse test
Into the test databasedb.createCollection('user')
Create auser
collection- Briefly outline the concept set, Mongo non-relational database, the concept does not exist in the table, and is set to correspond to the table. Of course, not a collection of tables, and the tables vary greatly, there is no table of ranks of the structure, you can simply put the collection as a list, and the list which will put one object. There are not found that like most of the json data format.
db.user.insert({name: 'zhangsan', age: 21, sex: 'male'})
Inserted in a data setdb.user.find()
All data in the user view the collectiondb.user.find().pretty()
Display data in the format of a nice pointdb.user.find({name: 'zhangsan'})
Find first parameter is the selection condition where the display data that meets the entire name = 'zhangsan' ofdb.user.find({name: 'zhangsan'}, {name: 1})
The first parameter is specified find display to show qualified name, 1 is a 0 is not displayed.
Use mongoose
mongoose is a nodejs tool library, easy to use nodejs operation mongodb
1. First Use mongoose database connection mongodb
const mongoose = require('mongoose');
// 创建一个连接,并监听各种事件,在执行connect操作时,各事件会视具体情况而触发。
mongoose.connection
.on('error', function (err) {
// 数据库连接失败时触发
console.log('connect error: ', err);
})
.on('disconnected', function () {
// 数据库断开时触发,断开重连的逻辑可以放在这里。
})
.once('open', function () {
// 数据库连接成功时触发,express开启listen的逻辑可以放在这里。
});
// 启动mongod服务默认是运行在127.0.0.1上,所以下面路径是localhost
// test是数据库名,如果有则连接,如果无则创建
mongoose.connect('mongodb://localhost/test', {
useNewUrlParser: true,
useUnifiedTopology: true
});
2. Schema and Model
In the mongoose in Schema, Model is a very important concept. Model mongodb the corresponding set collection
, and a set of corresponding structures Schema, which is the type field, fields are combined, if required, whether there is a default value and the like.
const UserSchema = mongoose.Schema({
name: String,
age: Number,
sex: Boolean
});
// Schema的静态方法
UserSchema.statics.findUserByAge = function (age) {
// 用then来拿到结果,如findUserByAge(21).then((res) => {})。
// 也可以在find第二个参数传回调函数
return this.find({'age': age});
}
// Schema的实例方法
UserSchema.methods.findUserByName = function(name) {
return this.model('User').find({ name: name });
};
// 创建一个Model,第三参数指定mongodb中collection的名字,如果不传则默认为变为复数(即Users)
const User = mongoose.model('User', UserSchema, 'user');
// 创建一条数据
// 1. 直接用User创建
User.create({name: 'zhangsan', age: 27, sex: true}, function(err, info) {
console.log(info);
});
// 2. 新创建一个对象再添加数据到数据库
// 再次说明下现在mongoose默认是支持promise方式的,可以使用then 或 回调函数的方式
var person = new User({name: 'lisi', age: 20, sex: false});
person.save().then(res => {
console.log(res);
})
// 调用Schema中定义的静态方法,可以通过User直接调
User.findUserByAge(21);
// 调用Schema中定义的实例方法方法,先实例化再调
const user = new User();
user.findUserByName('zhangsan');
// 删除数据,删除符合条件的一条
User.deleteOne({name: 'lisi'}).then();
// 删除符合条件的所有数据
User.deleteMany({age: 20}).then();
// 注意:remove()方法已经被弃用了!
Finally, attach the mongoose api documentation, the use of other methods are not listed:
EVERYTHING
Mentioned above is the current project has been used, follow-up is likely to continue to expand:
- docker and mongodb
- mongodb automatically copied set of disaster recovery