在Express路由器中使用两个MongoDB集合,可以按照以下步骤进行操作:
mongoose
。mongoose.connect()
方法连接到MongoDB数据库。例如:const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true });
users
和products
,可以创建两个模型:const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
});
const productSchema = new mongoose.Schema({
name: String,
price: Number,
description: String
});
const User = mongoose.model('User', userSchema);
const Product = mongoose.model('Product', productSchema);
const express = require('express');
const router = express.Router();
router.post('/users', (req, res) => {
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
newUser.save()
.then(user => {
res.json(user);
})
.catch(err => {
res.status(500).json({ error: err.message });
});
});
router.post('/products', (req, res) => {
const newProduct = new Product({
name: req.body.name,
price: req.body.price,
description: req.body.description
});
newProduct.save()
.then(product => {
res.json(product);
})
.catch(err => {
res.status(500).json({ error: err.message });
});
});
module.exports = router;
以上代码示例了如何在Express路由器中使用两个MongoDB集合。你可以根据实际需求进行修改和扩展。请注意,这只是一个简单的示例,实际应用中可能需要更多的错误处理和验证逻辑。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云