Created
September 25, 2012 13:30
-
-
Save donnut/3781861 to your computer and use it in GitHub Desktop.
Example of limiting the number of populated documents with where() and elemMatch
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 requirejs = require('requirejs') | |
, mongoose = require('mongoose'); | |
requirejs.config({ | |
baseUrl: __dirname | |
, nodeRequire: require | |
}); | |
requirejs([], function() { | |
mongoose.connect('localhost/mydb'); | |
var fixtures = null; | |
describe('Returning Comments', function() { | |
before(function(done) { | |
fixtures = require('pow-mongodb-fixtures').connect('mydb'); | |
fixtures.clearAllAndLoad(__dirname + '/fixtures', function() { | |
done(); | |
}); | |
}); | |
describe('posts and comments', function() { | |
it('get identified comments of post only', function(done) { | |
var Schema = mongoose.Schema; | |
var CommentSchema = new Schema({ content: [String] }); | |
var PostSchema = new Schema({ comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }] }); | |
var Comments = mongoose.model('Comment', CommentSchema); | |
var Posts = mongoose.model('Post', PostSchema); | |
var comment1 = new Comments({ content: 'eerste regel' }); | |
comment1.save(function(err) { | |
var comment2 = new Comments({ content: 'tweede regel' }); | |
comment2.save(function(err) { | |
var post = new Posts(); | |
var commentIds = [comment1._id, comment2._id]; | |
console.log('ids: '+commentIds) | |
post.comments.push(comment1); | |
post.comments.push(comment2); | |
post.save(function(err) { | |
var postId = post._id; | |
Posts.findById(postId) | |
.populate('comments') | |
.where('comments', { $elemMatch: {$in: commentIds }}) | |
.exec(function(err, doc) { | |
console.log(doc.comments); | |
done(); | |
}); | |
}); | |
}) | |
}); | |
}); | |
after(function() { | |
fixtures.clear(function() {}); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment