Skip to content

Instantly share code, notes, and snippets.

@bnoguchi
Created June 9, 2011 08:12
Show Gist options
  • Save bnoguchi/1016303 to your computer and use it in GitHub Desktop.
Save bnoguchi/1016303 to your computer and use it in GitHub Desktop.
How to get mongoose GH-230 examples working without errors
// 'test pushing simple embedded documents into a document'
var mongoose = require('mongoose')
, should = require('should')
, Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var EmbeddedSchema = new Schema({
title : String
});
var ParentSchema = new Schema({
embeds : [EmbeddedSchema]
});
var Parent = mongoose.model('Parent', ParentSchema);
var cleanData = {
title : "Some string"
};
var parent = new Parent(cleanData);
parent.embeds.push(cleanData, cleanData, cleanData);
parent.save(function(err){
process.nextTick(function(){
parent.embeds.should.have.length(3);
mongoose.disconnect();
})
});
// 'test pushing embedded documents with dirty attributes into a document'
var mongoose = require('mongoose')
, should = require('should')
, Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var EmbeddedSchema = new Schema({
title : String,
someObj : {}
});
var ParentSchema = new Schema({
embeds : [EmbeddedSchema]
});
var Parent = mongoose.model('Parent', ParentSchema);
var parent = new Parent();
var dirtyData = {
title : "Some string",
someObj : {
aString : "bleh!",
aDate : Date.now()
}
};
parent.embeds.push(dirtyData, dirtyData, dirtyData);
parent.save(function(err){
process.nextTick(function(){
parent.embeds.should.have.length(3);
mongoose.disconnect();
})
});
// Using the schema.js example...
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
/**
* Schema definition
*/
// recursive embedded-document schema
var CommentsSchema = new Schema();
CommentsSchema.add({
title : { type: String, index: true }
, date : { type: Date, default: Date.now }
, body : String
, comments : [CommentsSchema]
});
var BlogPostSchema = new Schema({
title : String
, slug : String
, date : { type: Date, default: Date.now }
, comments : [CommentsSchema]
});
/**
* Define model.
*/
var BlogPost = mongoose.model('BlogPost', BlogPostSchema);
var post = new BlogPost({title: "test", body: "test"});
post.save(function(err){
if (err)
console.log(err)
else {
post.comments.push({title: "test", body: "woot woot"}, {title: "test2", body: "woot woot"});
post.save(function(err){
console.log(err);
console.log(post.comments)
mongoose.disconnect();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment