使用Mongoose,查询文档与子文档输入

时间:2015-08-11 07:57:29

标签: javascript node.js mongodb mongoose

我试图使用mongoose查询我的mongodb数据库:

DimensionModel.find({details:details}, function(err, obj) {
    console.log("object : "+obj);
});

请记住我的模型看起来像这样:

var DimensionSchema = new Schema({
  label:String,
  details:Schema.Types.Mixed
});

所以基本上,我想要的是使用作为子文档的细节来查询文档。 我现在得到空洞的结果,并且不明白为什么

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

我不确定你作为查询传递的是什么,但这个例子正在运行:

var DimensionSchema = new mongoose.Schema({
    label:String,
    details:mongoose.Schema.Types.Mixed
});

mongoose.model('Dimension', DimensionSchema);

var DimensionModel = mongoose.model('Dimension');

//First let's add a model with the details, than we could find it
var newDimensionModel = new DimensionModel()
newDimensionModel.details = {someDetails:"some details"}
newDimensionModel.save(function(err){
    if(err){
        return;
    }

    //Then we can query it
    DimensionModel.find({details:{someDetails:"some details"}}, function(err, obj) {
        console.log("object : 1" +obj);
    });
});

修改 如果您的详细信息对象更复杂,您也可以这样做: 在此阅读更多信息:http://docs.mongodb.org/manual/reference/method/db.collection.find/

var details = {
    "detail":"Some detail",
    "detail1":2,
    "detail2":2.5,
    "detail3":{"innerDetail":"detail"}
}

DimensionModel.find({"details.detail":"Some detail", "details.detail1":2, "details.detail2":2.5, "details.detail3":{"innerDetail":"detail"}}, function(err, obj) {
        console.log(obj.length);
    });