Mongoose TypeError:不能使用'in'运算符来搜索[object Object]中的'_id'

时间:2013-06-13 14:41:54

标签: node.js mongodb mongoose

我是mongodb的新手,在过去的几天里,我一直试图让我的参赛作品进入我的mongolab实例,但没有任何运气。当我执行保存调用时,我得到一个错误说明:

TypeError: Cannot use 'in' operator to search for '_id' in [object Object]

他们所指的[object Object]是我的Color架构。我还没有找到答案,并认为我会在这里发布并行工作,而我的研究更多。我已经粘贴了我正在使用的内容,希望这只是我正在做的事情。 TIA!

mongoose.connect(config.db.mongodb);
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var Color = new Schema({
     hex    :   {type:String, required: true, trim: true}
    ,perc   :   {type:String, required: true, trim: true}
});
var Img = new Schema({
     path   :   {type:String, required: true, trim: true}
    ,color  :   [Color]
});
var imgModel = mongoose.model('Img', Img);

exports.addImage = function(req,res){
    //First check to see if we already have the image stored
    imgModel.findOne({path: req.query.path}, function(error, image){
        if(error){ 
            console.log("Error");
            res.json(error);
        }
        else if(image === null){
            //There is no image so just store the info
            var image_data = {
              path:     req.query.path,
              color:    req.query.color
            };

            var img = new imgModel(image_data);

            img.save(function(error, data){
                //*** This error block below is where I am 
                //    entering and the message is displayed
                if(error){
                    console.log("Oh noo: ",error);
                    res.json(error);
                }
                else{
                    console.log("Saving: ",data);
                    res.json(data);
                }
            });
        } else{
            //The path is already here
            //res.json("Image already in db");
            console.log("Image already in db");
        }
    });
};

1 个答案:

答案 0 :(得分:2)

所以这是由于我的颜色对象在处理请求时未转义的方式。在进入它时,它看到了对象,但嵌套值无效,因此它正在抛出写入数据db,因为它正在期待字符串。我最后做了一个POST,然后在数据参数中传递json对象,然后通过正文读取它,它按预期工作,并根据需要自动创建数据库。感谢诺亚的回应!