Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aheckmann/3640687 to your computer and use it in GitHub Desktop.
Save aheckmann/3640687 to your computer and use it in GitHub Desktop.
using the $elemMatch projection with mongoose
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var assert = require('assert')
console.log('\n===========');
console.log(' mongoose version: %s', mongoose.version);
console.log('========\n\n');
var dbname = 'testing_1085';
mongoose.connect('localhost', dbname);
mongoose.connection.on('error', function () {
console.error('connection error', arguments);
});
var schema = new Schema({
items: [Number]
});
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
var a = new A({ items: [1,3,5,7,9] });
a.save(function (err, a) {
if (err) return done(err);
//A.findOne({ _id: a._id, items: { $elemMatch: {$in: [1,5,9] }}}).exec(function (err, docs) {
A.findOne({ _id: a._id }).select({ items: { $elemMatch: {$in: [1,5,9] }}}).exec(function (err, doc) {
console.log(doc); // { _id: 50478c35889a450000000001, items: [ 5 ] }
done(err);
});
})
});
function done (err) {
if (err) console.error(err.stack);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment