Created
July 1, 2011 23:52
-
-
Save bnoguchi/1059598 to your computer and use it in GitHub Desktop.
mongoose GH-341.js - Response to sebm
This file contains 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
var mongoose = require('mongoose') | |
mongoose.connect('mongodb://localhost/sebtest'); | |
var Schema = mongoose.Schema; | |
var StackItemSchema = new Schema({ | |
blob: Number | |
}); | |
var StackSchema = new Schema({ | |
name: String | |
, items: [StackItemSchema] | |
}); | |
var Stack = mongoose.model('Stack', StackSchema); | |
function addItems (stack) { | |
console.log("The stack is ..."); | |
console.log(stack); | |
console.log("\n"); | |
console.log('Gonna add some items now'); | |
stack.items.push({ blob:Math.random() }); | |
console.log("... added an item. stack looks like ..."); | |
console.log(stack); | |
console.log("\n"); | |
stack.save( function (err, stack) { | |
if (err) throw err; | |
console.log("item push persisted to mongodb") | |
console.log(stack) | |
console.log("\n"); | |
console.log("removing the item"); | |
stack.items[0].remove(); | |
console.log(stack); | |
console.log("\n"); | |
stack.save( function (err, stack) { | |
if (err) throw err; | |
console.log("removal persisted to mongodb"); | |
console.log(stack); | |
mongoose.disconnect(); | |
}); | |
}); | |
} | |
Stack.findOne({name:'The Stack'}, function (err, stack) { | |
if (err) throw err; | |
if (!stack) { | |
return Stack.create({name: 'The Stack'}, function (err, stack) { | |
if (err) throw err; | |
addItems(stack); | |
}); | |
} | |
return addItems(stack); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks so much for the example! This is a big help, I will be more conscientious of my JS code's need to be asynchronous and properly-scoped.