Created
September 5, 2012 17:31
-
-
Save aheckmann/3640687 to your computer and use it in GitHub Desktop.
using the $elemMatch projection with mongoose
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'); | |
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