使用mongoose控制器路由将两个mongodb集合连接在一起的步骤如下:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
// 其他字段...
});
const PostSchema = new Schema({
title: String,
content: String,
// 其他字段...
});
const User = mongoose.model('User', UserSchema);
const Post = mongoose.model('Post', PostSchema);
const User = require('../models/user');
const Post = require('../models/post');
// 获取所有用户和对应的帖子
const getUsersWithPosts = async (req, res) => {
try {
const users = await User.find().populate('posts');
res.json(users);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
};
// 创建新用户和帖子
const createUserWithPost = async (req, res) => {
try {
const { name, email, title, content } = req.body;
const user = new User({ name, email });
const post = new Post({ title, content });
user.posts.push(post);
await user.save();
res.json({ message: 'User and post created successfully' });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
};
module.exports = {
getUsersWithPosts,
createUserWithPost,
};
const express = require('express');
const router = express.Router();
const controller = require('../controllers');
router.get('/users', controller.getUsersWithPosts);
router.post('/users', controller.createUserWithPost);
module.exports = router;
const express = require('express');
const app = express();
const router = require('./routes');
app.use(express.json());
app.use('/api', router);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
现在,当访问/api/users
时,将返回所有用户和对应的帖子。当发送POST请求到/api/users
时,将创建一个新用户和帖子,并将它们连接在一起。
请注意,这只是一个简单的示例,实际应用中可能需要更复杂的逻辑和错误处理。另外,这里没有提及腾讯云的相关产品和链接地址,因为要求答案中不能提及亚马逊AWS、Azure、阿里云、华为云、天翼云、GoDaddy、Namecheap、Google等流行的一些云计算品牌商。
领取专属 10元无门槛券
手把手带您无忧上云