【问题标题】:Mongoose searching on array subdocument ObjectId not workingMongoose 在数组子文档 ObjectId 上搜索不起作用
【发布时间】:2014-07-21 14:01:16
【问题描述】:

这真的让我发疯了。问题来了:

我在 Mongoose 中运行以下查询:

s.findSubdocument=function(uid, cb)
{
     this.model('User').find({"flwng._id":uid.toString()}).select('flwng').exec(cb);
}

在以下用户架构上:

var userSchema= new mongoose.Schema(
    {
        uname:{type:String, index:{sparse:true, unique:true, dropDups:true}}, //the username
        email:String,
        pwd:{type:String},
        flwng:[{_id : {type : mongoose.Schema.ObjectId},uname : String}], //_id of users I am following
        flwrsz:Number,
        flwngsz:Number,
        feedsz:Number,
    }, {j: 1});//j:1 means guarantee it is written to the journal.

userSchema.set('autoIndex', true);
userSchema.index({"fid":1}, {sparse:true, unique:true, dropDups:true});
userSchema.index({"flwng._id" : 1});

其中 uid="53c4f16c431247694f0000a3" ==> 但我得到一个空数组:(

当我在 mongo shell 中运行相同的查询时:

db.users.find({"flwng._id":"53c4f16c431247694f0000a3"});

我得到了正确的结果集。我尝试了在“flwng._id”上使用和不使用索引和模式,我试图删除索引,reIndex,我现在已经没有想法了。我对 Mongoose 做错了吗?

任何帮助将不胜感激 - 谢谢! 亨利

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您在 mongodb 中的现有文档与您的架构不匹配。您的数据有记录,其中flwng._id 是一个字符串,这就是您在 mongo shell 中获得结果的原因。但是您的 mongoose 架构将其定义为 ObjectId,因此当您使用 mongoose 进行查询时,mongoose 会将您的字符串值转换为 ObjectId,并且查询不匹配。编写迁移以修复现有数据或更新架构以匹配您的数据在 String 与 ObjectId 数据类型方面,事情应该开始通过猫鼬工作。

    【讨论】:

    • 你是对的!我将 flwng 更改为 flwng:Array,现在它返回了正确的结果集。您建议将现有字符串转换为 ObjectID 的策略是什么?我尝试循环遍历结果并将值转换为这样但没有运气: users[i].flwng[j]._id=new mongoose.Types.ObjectId(sUid);用户[i].save()
    • 开始工作了!谢谢彼得。对于那些遇到类似问题的人,我得到了 String -> ObjectId 迁移以在 Mongoose 中使用以下查询:this.model('User').update({"flwng._id":uid.toString()}, { "flwng.$._id":uid},{multi:true}).exec(cb);
    猜你喜欢
    • 2022-12-12
    • 2011-12-14
    • 2014-09-11
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多