Skip to content

Instantly share code, notes, and snippets.

@paduc
Created September 3, 2011 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paduc/1190969 to your computer and use it in GitHub Desktop.
Save paduc/1190969 to your computer and use it in GitHub Desktop.
Use Mongoose in Node
// Database
var mongoose = require('mongoose');
// connect to the db, test is the default db name (type db in the mongo shell to see yours)
mongoose.connect('mongodb://localhost:27017/test');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
ThingSchema = new Schema({
'_id': ObjectId,
'a': String
});
// 'Thing' is the name of the mongo collection
var Thing = mongoose.model('Thing', ThingSchema);
// creating a new Thing
var newThing = new Thing({a:'hello world'});
newThing.save(function(err){
// saving is asynchronous
if(err) console.log("Something went wrong while saving the thing);
else console.log("Thing was successfully saved");
});
// retrieving all Things
Thing.find({ /* mongo selectors go here */ } , function(err,docs){
// find is also async
// docs contains all the results
// err contains the error if any
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment