【问题标题】:mongoose: getting unknown objectId when stored string instead of objectId猫鼬:在存储字符串而不是objectId时获取未知的objectId
【发布时间】:2020-10-25 01:44:14
【问题描述】:

据我说,当我按下“ABC”而不是 objectId 时,它应该显示一些错误,例如

对于路径“likes”处的值“ABC”,转换为 ObjectId 失败。

但是当我打印更新的数据时,我在 likes 数组中看到了一些未知的 objectId

我的问题是,未知的 objectId(6a61736f6e20626f75726e65) 是什么以及为什么会生成它 自动


用户模型

  new Schema({
            name: { type: String,required:true},
    }, { usePushEach: true ,timestamp:true});

饲料模型

new Schema({
        user: { type: Types.ObjectId, ref: 'user', required: true },
        name: { type: String,default:null, trim: true },
        likes: [{ type : Types.ObjectId, ref: 'user',}],
}, { usePushEach: true ,timestamp:true});

在 Feed Schema 中,点赞参考了 User Schema
var data = await feed.findByIdAndUpdate(
                 postId, 
                { 
                 $push: { likes: 'ABC' }
                }
           );




        if(data){
         var data = await feed.findById(postId);
         console.log(data.likes);//["6a61736f6e20626f75726e65"]
        }
        OutPut:
        ["6a61736f6e20626f75726e65"]

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    由于您在likes 中推送不是ObjectId 的String,因此您会收到此错误。

    您的架构明确指出喜欢是array of ObjectId:

    likes: [{ type : Types.ObjectId, ref: 'user'}],
    

    所以你必须传递一个ObjectId 而不是用户的name。

    你必须这样做:

    // Whenever you are pushing value in `likes` `array`, 
    // you need to get the `ObjectId` of the user who liked the feed.
    
    let userId =  <userId_of_Ishwar>;
    var data = await feed.findByIdAndUpdate(
         postId, 
         { 
             $push: { likes: userId }
         });
    

    【讨论】:

    • 我问为什么我推字符串的时候会自动生成unknown objectId
    • 我知道我必须在那里传递 objectId,
    • 对不起,我误读了这个问题,但findOneAndUpdate 不会返回更新的对象,除非{new : true} 作为/in 选项传递。所以我想,您正在打印的 ID 是更新之前已经存在的 ID。您可以通过在 .findOneAndUpdate() 之前和之后执行 .find() 来验证这一点
    猜你喜欢
    • 2016-11-21
    • 2016-01-01
    • 2013-03-24
    • 2021-03-27
    • 2017-04-06
    • 2015-12-13
    • 2012-03-18
    • 1970-01-01
    • 2021-01-12
    相关资源
    最近更新 更多