# 设计数据模型

在使用mongodb数据库中需要使用到各种集合，一开始我的做法是将所有的集合都写在一个collection-init.js文件中，后来发现这样不利于维护，同时在使用某一个特定集合时还需要将其他集合加载进来。于是针对不同的数据模型将其封装在不同的文件中

```javascript
var mongoose=require("mongoose")
var Schema=mongoose.Schema  //用于定义数据集的表结构


var studentSchema=new Schema(
    #定义数据集

)
#导出封装好的数据集
module.exports=mongoose.module("Student",studnetSchema)
```

## 在针对该数据模型的方法文件中使用该数据结构

```javascript
var students_Col=require("./../database/modules/students_module.js")  //加载数据库集合结构文件
#基于数据模型就可以对数据进行增删改查
exports.insert=function(){

}
exports.findOne=function(){}
exports.findAll=function(){}
exports.update=function(){}
exports.delete=function(){}
```

## 只需要连接一次数据库

```javascript
var mongoose=require("mongoose")
var dbcongigure=require("./../configure.js") //加载数据库配置信息
mongoose.connect(dbcongigure.dbUrl,dbcongigure.dbOption,function(err){
    if(err){
        throw(">>>>>>>>failed to connect MongoDatabase<<<<<<\n"+err);
    }
})
```

* 在app.js文件中进行数据库的连接和路由的配置
* 在路由文件中使用对应模型的方法
* 在模型方法文件中使用事先定义好的数据模型

> 最后实现每一种数据类型对应了一个数据处理函数，而一种功能的实现依赖于一个路由文件，路由文件中使用多个数据模型与数据处理函数


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zpliu.gitbook.io/booknote/node/mongodb/shu-ju-mo-xing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
