Created
December 4, 2012 17:58
-
-
Save vicapow/4206893 to your computer and use it in GitHub Desktop.
mongoose casting object ids of type string to ObjectId()
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') | |
, db = mongoose.createConnection('localhost', 'test') | |
var CommentSchema = mongoose.Schema({ | |
title : 'string' | |
}) | |
var PostSchema = mongoose.Schema({ | |
name: 'string' | |
, comments : [CommentSchema] | |
}) | |
var Post = db.model('Post',PostSchema) | |
Post.collection.drop() | |
var post = new Post({ | |
name : 'some post' | |
, comments : [ | |
{ | |
title : 'Comment 1' | |
} | |
, { | |
title : 'Comment 2' | |
} | |
] | |
}).save(function(err, post){ | |
if(err) throw err | |
var post_id = post._id | |
, comment_id = post.comments[0]._id.toString() | |
console.log('post') | |
console.log(post) | |
Post.update( | |
// id of the post to update | |
{ _id : post_id } | |
// the `update` query to run | |
, { | |
$pull : { | |
comments : { _id : comment_id } | |
} | |
} | |
// the callback | |
, function(err, numEffected){ | |
if(err) throw err | |
console.log('numEffected') | |
console.log(numEffected) | |
Post.findById(post_id, function(err, post){ | |
console.log(post) | |
process.exit() | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment