express连接mongoDB实例

1.创建连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// utils/mongoConfig.js

const mongoose = require('mongoose');

// 创建连接实例
const mongoUrl = 'mongodb://admin:123456@127.0.0.1:27017/express-test?authSource=admin';
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });

// 创建User集合连接
const UserSchema = mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', UserSchema, 'user');


// 创建student集合连接
const StudentSchema = mongoose.Schema({
name: String,
grade: Number,
class: String
});
const Student = mongoose.model('Student', StudentSchema, 'student');

module.exports = {
User,
Student
};

2.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// routers/index.js

router.get('/mongo', async (req, res) => {
const result = await User.aggregate([
{
$lookup: {
from: 'student',
localField: 'name',
foreignField: 'name',
as: 'item'
}
},
{ $project: {'name':1,'age':1,'item.grade':1,'item.class':1} },
{
$group: { _id:"$item.class", count:{$sum: 1} }
}
])
res.send(result);
})

Comments