Skip to content

Instantly share code, notes, and snippets.

@nathanallen
Last active July 19, 2016 21:49
Show Gist options
  • Save nathanallen/976ebd5d1acf742d71f82924d2fe6e3b to your computer and use it in GitHub Desktop.
Save nathanallen/976ebd5d1acf742d71f82924d2fe6e3b to your computer and use it in GitHub Desktop.
Cheatsheets

Mongoose Cheatsheet

Schemas

The permitted SchemaTypes are:

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var userSchema = new Schema({
  username: String,
  email: {
    type: String,
    required: true,
    lowercase: true,
    trim: true,
    unique: true
  }
});

var User = mongoose.model("User", userSchema);

var blogPostSchema = new Schema({
  _user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  created_at: {
    type: Date,
    default: Date.now
  },
  title: String,
  body: String
})

var BlogPost = mongoose.model("BlogPost", blogPostSchema);

Converting to JSON

Mongoose records will display as [Object object] when console.logged (this is new behavior). Here are options:

  • JSON.stringify(record) -- ugh
  • record.toJSON() — best
  • db.Record.findOne({}).lean().exec(function(err, rec){ console.log(rec) }) — good but confusing (lean() converts instance to object)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment