---
title: "mongoose简单使用样例"
author: "ully"
date: "2012-03-09T12:59:20Z"
tags: []
categories: ["开源软件"]
slug: "mongoose"
draft: false
lastmod: "2012-04-01T13:46:49Z"
id: 1447625
url: "https://ully.iteye.com/blog/1447625"
---

**新建文件 app.js**

内容如下：

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

mongoose.connect('mongodb://localhost/test');

1.定义schema，也就是传统意义的表结构
var BlogSchema = new Schema({
   user_id        : {type : Number, index : true}
  ,username       : {type : String}
});
2.定义model
mongoose.model("Blog", BlogSchema);
//mongoose.model("Blog", BlogSchema,"BLOG");  model名，绑定的schema，db collection名

3.日常操作

var Blog = mongoose.model("Blog"); //获得model实例

var blog1 = new Blog();
blog1.id = 4;
blog1.title="ully";

blog1.save(function(err) {  //存储
  if (err) {
    console.log('save failed');
  }
  console.log('save success');
});

Blog.find({id:4},function(err,docs){
     console.log(docs);
});

Blog.remove({id:4},function(err,docs){
     console.log(docs);
});

Blog.update({id:4,title:"ulii"},function(err,docs){
     console.log(docs);
});
```

 

执行 node app.js  即可