在mongoose中_id搜索的结果为null

时间:2015-10-31 17:48:12

标签: mongodb mongoose

[]

我在mongoose中找到{parentId: cat._id} res
var ObjectId = Schema.ObjectId;
var CategorySchema = new Schema({
    name: String,
    slug: String,
    parentId: {type: ObjectId, required: false},
    ancestors: {
        type: [{
            _id: ObjectId,
            name: String,
            slug: String
        }], required: false
    }
});

CategorySchema.statics.getNested = function(parentSlug,cb){
    this.findOne({slug:parentSlug},function(err,cat){
        if (err) {
            cb(err);
        } else {
            this.find({parentId: cat._id},function(err, cats){
                console.log(cats);
                if (err){
                    cb(err);
                } else {
                    cb(null,cats);
                }
            });
        }
    });
};

我尝试了{parentId: ObjectId(cat._id)},但这也不起作用// ObjectId(cat._id) -> undefined

如何通过_id搜索mongoose?

更新<!/强>

查询

Category.find({parentId:'5634eeb38a33a59c1dffa6ee'}, function(err,res){
    console.log(res);
});

工作正常,但如何?

2 个答案:

答案 0 :(得分:0)

应为min-height: -moz-min-content; // not implemented min-height: -webkit-min-content // works for opera and safari min-height: min-content // works for chrome

答案 1 :(得分:0)

您的架构中有不正确的ObjectId类型,您应该使用Schema.Types.ObjectId而不是Schema.ObjectId,因为它们返回不同的值:

http://mongoosejs.com/docs/api.html#schema-objectid-js http://mongoosejs.com/docs/api.html#types-objectid-js

如果将ObjectId定义替换为以下

var ObjectId = Schema.Types.ObjectId;

您的代码应该正常运行。