Skip to content

Instantly share code, notes, and snippets.

@vicapow
Created December 4, 2012 17:58
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 vicapow/4206893 to your computer and use it in GitHub Desktop.
Save vicapow/4206893 to your computer and use it in GitHub Desktop.
mongoose casting object ids of type string to ObjectId()
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