Long time listener first time caller :-)
I've searched for a considerable amount of time and haven't quite found an answer to my problem here. I'm looking for a way, or would like to know the "proper" way, to only return a specific item within a nested mongoose Schema.
So lets say I have this example.
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var conn = mongoose.connect('mongodb://localhost/testjs');
Bar = new Schema({
text: String
});
Foo = new Schema({
bar: [Bar]
});
var Foo = mongoose.model('Foo', Foo);
// Clean up the DB
Foo.find({}, function(err, res) {
for (i in res) {
res[i].remove()
}
});
var foo = new Foo()
foo.bar.push({"text":"Hi"})
foo.bar.push({"text":"Bye"})
foo.bar.push({"text":"Hey"})
foo.save(
function(err){
var r = Foo
.where('bar.text').equals('Hi')
.select('bar.text')
.exec(function(err, res) {
console.log(res)
})
}
);
Result
[ { _id: 546c235cea0f16dc0d85a60f,
bar: [ { text: 'Hi' }, { text: 'Bye' }, { text: 'Hey' } ] } ]
From the query I would've expected it to only return
[ { _id: 546c235cea0f16dc0d85a60f,
bar: [ { text: 'Hi' } ] } ]
So I guess that leads me to a few questions:
- Is there a better way this query should be constructed?
- Is this typical behavior and it's up to be to loop over the results and just pull out what I need?
- For the original query, why would it return all fields rather than what I've specified in the 'where' statement?