# BasicTo-mongoose

# 官网

http://mongoosejs.com/index.html

# What is moogoose?

elegant mongodb object modeling for node.js

为nodejs提供的简洁的mongode对象模型

# 为什么使用mongoose?

Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose.

因为写一个mongodb的验证,业务逻辑是很麻烦的,所以我们使用Mongoose

# 安装

$ npm install mongoose

# 怎样使用?

前提:First be sure you have MongoDB and Node.js installed. 首先需要安装好,mongodb和node.js

# step1 引入并且链接数据库

// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

# step2 添加错误信息

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  // yay!
});

其余的数据库的操作信息就写在db.once('open')的回掉函数中

# Step3 设置Schema

With Mongoose, everything is derived from a Schema (opens new window).

Mongoose 的一切都派生自Schema

# 什么是Schema?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Mongoose 的一切以SChema开始。每一个Schema映射一个MongoDB的集合,并且在这个集合种定义了这个集合的文档结构

# 怎么定义?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

# step4 设置Modal

# 什么是modal?

A model is a class with which we construct documents.

一个modal是一个我们构建文档的类。

# 怎么定义

var blog = mongoose.model('Blog', BlogSchema);

# step5 设置实例(记录)

一个实例可以理解为是一条记录

var sialvsic = new blog({ name: 'Silence' });
console.log(silence.name);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');

var Cat = mongoose.model('Cat', { name: String });

var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
  if (err) // ...
  console.log('meow');
});
陕ICP备20004732号-3