Step into Mongoosejs - step II

Mongoose: elegant MongoDB object modeling for node.js.

Data Types

  • String, utf-8 encoded
  • Number, MongoDB support long and double, but mongoosejs does not
  • Boolean, true or false
  • Date (ISODate object, expires, min, max )
  • Buffer (.copy(target), .equals(other), .writer())
  • ObjectId ( var id = new mongoose.Types.ObjectId;)
  • Array ([] or schema; #$shift(), #remove(), .$pop(), .addToSet([args…]), .indexOf(obj), inspect(), .nonAtomicPush([args…]) , .pop(), .pull([args…]), .push([args…]), .set(), .shift(), .sort(), .splice(), .toObject(options), .unshift() )
  • Mixed, (empty object {} or Schema.Types.Mixed )
  • custom SchemaTypes

Schema

Schema define data structure.

define schema early, just after require mongoose
easy to update schema even though data exit and no offline or down time

1
2
3
4
5
6
7
8
9
10
11
//define account schema, any website need the account information, even if an anonymous account
var accountSchema = new mongoose.Schema({
email: {type: String, unique: true},
password: String,
name: String,
createdOn: {type: Date, default: Date.now},
updatedOn: Date,
lastLogin: Date,
location: [],
...
});

Model

  • Model is comiled version of Schema, Schema + Model = Class of OOP
  • An instance of model maps to a document in a database of MongoDB
  • Collection coorespond to table of RDBMS,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//build Account model by default connection / class Account
mongoose.model('Account', accountSchema, 'accounts');
// or by specific connection
//connection1.model('Account', accountSchema);

//Instance, an instance of a model refers to a document
var myAccount = new Account({
email: 'myemailaddress@xxx.com',
password: 'pwd',
name: 'myName'
});

// or js code
myAccount.name = 'myNewName';

for code above, Model name is Account, Collection name is “accounts”.