【问题标题】:Mongoose TypeError: Cannot use 'in' operator to search for '_id' in [object Object]Mongoose TypeError:无法使用“in”运算符在 [object Object] 中搜索“_id”
【发布时间】:2013-06-10 00:13:14
【问题描述】:

我是 mongodb 的新手,在过去的几天里,我一直在尝试将我的条目放入我的 mongolab 实例中,但没有任何运气。似乎当我执行保存调用时,我收到一条错误消息:

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

他们所指的 [object Object] 是我的颜色模式。我还没有找到答案,我想我会在这里发帖,以便在我进行更多研究的同时并行工作。我已经粘贴了我正在使用的内容的片段,希望这只是我正在做的一些愚蠢的事情。蒂亚!

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");
        }
    });
};

【问题讨论】:

  • 你确定 req.query.path 返回一个有效值吗?输入console.log(req.query.path) 以确保值符合您的预期
  • 是的,它是我的图像的路径。抱歉,我删除了所有的 console.logs 以缩小帖子的内容。也许我应该把它们留在:) 需要注意的是,它在第​​一个错误块中没有错误。当我调用 img.save 时,它​​在错误块中出错。但是,在您发表评论后,我去检查了颜色对象的内容,我的值非常奇怪。我认为这可能是问题所在。我认为当我对传入的字符串进行转义时,它会弄乱一些东西。必须马上去开会。当我回来时会检查。谢谢!

标签: node.js mongodb mongoose


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 2013-04-05
    • 2013-01-15
    • 2018-05-10
    • 2018-05-17
    • 2018-05-02
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多