Created
September 3, 2011 10:22
-
-
Save paduc/1190969 to your computer and use it in GitHub Desktop.
Use Mongoose in Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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