读mongoose api 记录

mongoose 需要在Schemas基础上进行使用

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 }

});

ArrayJavaScript编程语言中并不是数组,而是集合,因此里面可以存入不同的值,以下代码等价:

    var ExampleSchema1 = new Schema({array:[]});
    var ExampleSchema2 = new Schema({array:Array});
    var ExampleSchema3 = new Schema({array:[Schema.Types.Mixed]});
    var ExampleSchema4 = new Schema({array:[{}]});

创建一个模块

var Blog =  mongoose.model('Blog',blogSchema);、

管理数据库的形式

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

mongoose 常用查询语句

 提供了find ,findOne , findById 用于文档查询

model.find(query,fields,options,callback) //fields,options 是可选参数

简单查询: model.find({'cursor':6},function(err,doc){})//doc 是查询后的语句

只查询指定键的结果 : model.find({},{'first','last'},function(err,docs){})//doc是只包含文档的第一个和最后一个键值

model.findOne 和 find 一样 但只返回单个文档。

model.findById 和 find 相同,但它只接受文档的_id 作为参数,返回单个文档

model.findById(obj._id,function(err,doc){})

model.count 返回符合条件的文档数

model.count(conditions,callback)

model.remove 删除符合条件的文档

model.remove(contions,callback)

model.where 查询比较复杂的时候 用where

modle .where('age').gte(25)

    .where('tags').in{['movie','music','art']}

    .select('name','age','tags'}

    .skip(20)

    .limit(10)

    .asc('age')

    .slaveOk()

...

model.update  更新数据库

var contions = {name : 'borne'},

  update = {$inc:{visits:1}},

  options = {multi : true}

model.update(conditions,update,options,callback)

原文地址:https://www.cnblogs.com/zerohu/p/5247883.html