Mongoose关于Schama与Connnect实例

一、npm安装Mongoose

$ npm install mongoose

连接我们本地的 test 数据库

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

connect() 返回一个状态待定(pending)的连接, 接着我们加上成功提醒和失败警告

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

连接成功时,回调函数会被调用。简洁起见, 我们假设下面所有函数都运行在这个回调函数里。

Mongoose 里,一切都始于Schema。 现在我们来看一个例子:

var kittySchema = mongoose.Schema({
  name: String
});

很好,我们得到了一个带有 String 类型 name 属性的 schema 。 接着我们需要把这个 schema 编译成一个 Model

var Kitten = mongoose.model('Kitten', kittySchema);

model 是我们构造 document 的 Class

var felyne = new Kitten({ name: 'Felyne' });
console.log(felyne.name); // 'Felyne'

二、创建表与MongoDB连接

Schema()  :创建Tables

Parameters

  • definition «Object»
  • [options] «Object»

Schema 构造函数。

示例:

var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number, children: [child] });
var Tree = mongoose.model('Tree', schema);

// 设置 schema 选项参数
new Schema({ name: String }, { _id: false, autoIndex: false })

Options:

  • autoIndex: bool - 缺省值 null (即使用数据库连接自带的 autoIndex 选项)
  • bufferCommands: bool - 缺省值 true
  • capped: bool - 缺省值 false
  • collection: string - 没有缺省值
  • id: bool - 缺省值 true
  • _id: bool - 缺省值 true
  • minimize: bool - 当 document#toObject 被手动调用时控制其行为 - 缺省值 true
  • read: string
  • safe: bool - 缺省值 true.
  • shardKey: bool - 缺省值 null
  • strict: bool - 缺省值 true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值