const express = require('express');
const app = express();
const mongoose =require('mongoose');
// 参数一为数据库地址,每一个数据库都是一个服务器,因此是一个网络地址。
// 本地可使用127.0.0.1或者localhost。
// 地址标准为 mongodb:// Ip地址 :端口号(默认为27017)/数据库名称(此处能够自定义,mongodb
// 会自动建立对应表)
// 注意第二个参数是新版本要求的。
// 数据库中,对应的东西须要分类存放,好比用户放在用户类中
// 在 mongdodb中,这个类叫作集合,一个集合中能够放不少行数据
// 相似 excel。
// 下面假设有一个产品表。对应 创建一个模型。表-模型-集合,能够同等看待。在mongodb中叫集合。
// 惯例,这个模型名字都是大写
// 参数一是模型名称,参数二是表结构。
// 参数二定义了表中的字段/属性,传递一个对象
const Product =mongoose.model('Product',new mongoose.Schema({
title:Number,
name:String
}));
// 测试用。
// Product.insertMany(
// [
// {title:1,name:'product1'},
// {title:2,name:'product2'},
// {title:3,name:'product3'}
// ]
// );
app.use(require('cors')())
app.use('/',express.static('public'))
app.get('/about',function(req,res){
res.send([
{page:'about'}
])
})
// 若是下面用了await,那么上面就要使用async
// 表示他是一个异步函数。 这是成对出现的。
app.get('/products',async function (req,res) {
// 每一次 数据库查询都是从Node数据库 的异步操做
// 因此要await
res.send(await Product.find())
})
app.listen(3000,()=>{
console.log("App is listening on port: 3000!")
})