Contents of this article
1. The basic perception of MongoDB
MongoDB
It is a non-relational database, no need to design tables, each table is a collection concept. After installation MongoDB
, open the terminal command line and enter the command to mongo
connect to the database, and you can use MongoDB
some commands under the command line : the connection is successful
as shown in the figure MongoDB
.
MongoDB
Some basic commands:
show dbs
View all databases
use 数据库名称
Switch to the specified database (it will be created if it does not exist). Show dbs will be displayed after inserting data.- Insert
db.students.insertOne({"name": "counterrr"})
data . - Check all the collections under the current data
show collections
. db.students.find()
Find outstudents
all the data under the collection.
2. Use MongoDB in Node.js
Use MongoDB
official packages mongodb
, official documents .
But we generally don't use this package for real development. Generally, a third party is mongoose
used for operation MongoDB
, and the third-party package is packaged based on the official mongodb
package. Next, we will mongoose
do the following based on demo
:
- Create a file on the desktop
mogoose-demo
, and then drag this folder to thevscode
editor. - Then open
vscode
the terminal command line, enter the command tonpm init -y
quickly generate the project specification. - Enter the command again
npm install mongoose
. Installmongoose
this package. - Create in the root directory
db.js
, enter the code:
Then we run it and enter it in the command// 引入mongoose const mongoose = require('mongoose'); // 连接MongoDB数据库 mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true}); // 创建模型,Cat这个模型它会自动生成一个cats集合,里面有name这个属性,并且是String类型的 const Cat = mongoose.model('Cat', { name: String }); // 实例化一个Cat const kitty = new Cat({ name: 'Zildjian' }); // 持久化保存 kitty.save().then(() => console.log('meow'));
node db.js
as follows:
successfully printed out. Then we went to the terminal command line to check:
found that there is data. Next, I loop it to generate 100 data and insert them into the database, the code is as follows:
// 引入mongoose
const mongoose = require('mongoose');
// 连接MongoDB数据库
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true, useUnifiedTopology: true});
// 创建模型,Cat这个模型它会自动生成一个cats集合,里面有name这个属性,并且是String类型的
const Cat = mongoose.model('Cat', {
name: String });
for(let i = 0; i < 100; i++) {
// 实例化一个Cat
const kitty = new Cat({
name: '喵喵' + i });
// 持久化保存
kitty.save().then(() => console.log('meow'));
}
Open the terminal to view: the
whole process is completely similar to the javascript
syntax. Very flexible, there are not so many rules and regulations to change.
Next, we create in the root directory db2.js
to practice the collection structure, the code is as follows:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost:27017/test', {
useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new Schema({
name: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
// 模型构造函数
const User = mongoose.model('User', userSchema);
-
In this
js
document, we have addedSchema
, that this is to set the framework of this collection, for example,name
and thepassword
field is theString
type of and is a must, and finally we publish this model constructorModel
toUser
, butMongoDB
will automatically generateusers
a set of upper case to lower case , The form of singular variable plural form generates a set. Open another terminal command and enter the commandmongod
to connect to the database. Success as shown below:
Next, we will add, delete, modify and check on this basis:
-Add:
(Add the following code to the original code)// 创造实例 const user = new User({ name: 'Counterrr', password: 'mongodb' }) // 存储实例 user.save().then((data) => { console.log('存储成功') console.log(data) }, () => { console.log('存储失败') })
Then enter the command line
node db2.js
:
we can see that the successful return parameter is the current data.
-Check:
We commented out the added code, and then added the following code on the original basis:// 查询所有 User.find((err, res) => { if (err) { console.log('查询失败') } else { console.log('查询成功') console.log(res) } })
Rerun
node db2.js
:
You can see that the query is successful. You can also query based on conditions, we insert another piece of data:// 创造实例 const user = new User({ name: '小红', password: 'mongodb' }) // 存储实例 user.save().then((data) => { console.log('存储成功') console.log(data) }, () => { console.log('存储失败') })
You can see that we inserted another piece of data, and then we commented out the code that stores Xiaohong above, and then we need to find out this piece of data named Xiaohong. The conditions are as follows:
// 查询小红 User.find({ name: '小红' }, (err, res) => { if (err) { console.log('查询失败') } else { console.log('查询成功') console.log(res) } })
Re-run
node db2.js
, the effect is as follows:
we can see that we have followed a condition{name: '小红'}
, in this case, Xiaohong will be queried.
-Delete:
We comment out the query code and enter the deleted code:User.deleteOne({ name: '小红' }).then((data) => { console.log('删除成功') console.log(data) }, (err) => { console.log('删除失败') console.log(err) })
Check the effect:
You can see that we are deleted successfully.
-Update:
Comment the delete code, enter the update code as follows:User.updateOne({ name: 'Counterrr' }, { name: 'Counter'}).then((data) => { console.log('更新成功') console.log(data) }, (err) => { console.log('更新失败') console.log(err) })
We
name
asCounterrr
updatedCounterrr
as:
go to the query:
has been changed.
More MongoDB CRUD interfaces Click for
good later we will useMongoDB
to write before our next student to re-reconstruction system. deepen impression.