Posted 2023-06-22Updated 2023-06-22nodejsa minute read (About 125 words)express连接mongoDB实例1.创建连接12345678910111213141516171819202122232425262728// utils/mongoConfig.jsconst 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.使用12345678910111213141516171819// routers/index.jsrouter.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);}) #nodejs