John Younan John Younan - 6 months ago 17
Node.js Question

Returning all fields from MonoDB matched by value of a field embedded in Object type

for the following MongoDB results, i'm trying to write a query where the name filed is NOT

Demo
or
Demo 2
the Items.location is
equal to hongkong
:

{
"_id": ObjectID("573ac4d1ad364cd534a03e15"),
"updatedAt": ISODate("2016-05-17T07:14:25.341Z"),
"createdAt": ISODate("2016-05-17T07:14:25.341Z"),
"name": "Testing",
"Items": {
"date": "18052016",
"location": "hongkong"
},
"__v": 0
},
{
"_id": ObjectID("573ac4d1ad364cd534a03e16"),
"updatedAt": ISODate("2016-05-17T07:14:25.341Z"),
"createdAt": ISODate("2016-05-17T07:14:25.341Z"),
"name": "Demo",
"Items": {
"date": "18052016",
"location": "hongkong demo"
},
"__v": 0
},
{
"_id": ObjectID("573ac4d1ad364cd534a03e16"),
"updatedAt": ISODate("2016-05-17T07:14:25.341Z"),
"createdAt": ISODate("2016-05-17T07:14:25.341Z"),
"name": "Demo 2",
"Items": {
"date": "18052016",
"location": "hongkong demo"
},
"__v": 0
}


My query looks like:

mySchema.statics.testing = function *() {
var output = this.find(
{
name: {
$nin: ["Demo", "Demo 2"]
}
}
,{
Items: {
$elemMatch: { location: "hongkong" }
}
}).exec();

return output;
};


and my schema is below:

var mongoose = require('mongoose');
var mySchema = new mongoose.Schema({
name: String,
Items: Object
}, { timestamps: true });


The query seems to only return the
"_id"
field for the matched where as i want the all the fields returned, name, Items..etc. What am i missing?

Answer

fixed. Needed:

var output =  this.find(
        {
            name: {
                $nin: ["Demo", "Demo 2"]
            },
            "Items.location" : "hongkong"
        }).exec();

    return output;
};