将MongoDB添加到Windows服务中
打开命令行运行
net start MongoDB
保持数据库的运行
//url是数据库连接的地址
const url = 'mongodb://localhost:27017/express-test'
//连接数据库
mongoose.connect(url, {
useNewUrlParser : true,
useUnifiedTopology: true
})
//创建一个对象
const Product = mongoose.model('Product', new mongoose.Schema({
title:String,
}))
添加数据
Product.insertMany([
{title: 'product1'},
{title: 'product2'},
{title: 'product3'},
])
列表页接口:
app.get('/products',async function(req,res){
//const data = await Product.find().limit(2)
const data = await Product.find().sort({_id: -1})
res.send(data)
})
访问http://localhost:8080/products/ 返回按照id排好序的Product列表
详情页接口:
app.get('/products/:id', async function(req, res) {
const data = await Product.findById(req.params.id)
res.send(data)
})
访问http://localhost:8080/products/5fa39e361ec90e34a8a1a7cc 返回列表页中的一个数据,按照id为索引。