对于以下MongoDB结果,我试图编写一个查询,其中名称字段不是Demo
或Demo 2
,而Items.location是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
}
我的查询如下:
mySchema.statics.testing = function *() {
var output = this.find(
{
name: {
$nin: ["Demo", "Demo 2"]
}
}
,{
Items: {
$elemMatch: { location: "hongkong" }
}
}).exec();
return output;
};
我的架构如下:
var mongoose = require('mongoose');
var mySchema = new mongoose.Schema({
name: String,
Items: Object
}, { timestamps: true });
查询似乎只返回匹配的"_id"
字段,因为我希望返回所有字段,name,Items..etc。我错过了什么?
答案 0 :(得分:0)
试试这段代码
mySchema.statics.testing = function (fn) {
this.find(
{
name: {
$nin: ["Demo", "Demo 2"]
},
"Items.location": "hongkong"
})
.exec(function (err, docs) {
fn(err, docs)
})
};
答案 1 :(得分:0)
固定。需要:
var output = this.find(
{
name: {
$nin: ["Demo", "Demo 2"]
},
"Items.location" : "hongkong"
}).exec();
return output;
};