猫鼬,获取字符串记录ID

Mongoose, get string record ID

我正在尝试使用 Nodejs 为 MongoDB 使用 Mongoose 设置数据库。当前,当它执行 findByID 时,它 returns 一个我似乎无法解析或转换为字符串的对象。我正在尝试将提供的用户 ID 与返回值进行比较,如下所示。 如何执行 FindBy.. 函数并获得字符串格式的结果,以便执行比较?谢谢

        globalTest = doc._id;
        
        //const foundUser = Auth.findById(mongoose.Types.ObjectId(doc._id));
        const foundUser = Auth.findById(mongoose.Types.ObjectId(globalTest));//.lean().exec();
    
        if(globalTest===foundUser){
            console.log('match');
        }else{
            console.log('no match');console.log(foundUser+' vs '+globalTest);              
        }
        console.log('BREAK: '+foundUser._id);//always undefined

控制台输出:

Saving: 622f6ed69f5b04b4c82fce74 no match
auth.findOne({ _id: new ObjectId("622f6ed69f5b04b4c82fce74") }) vs 622f6ed69f5b04b4c82fce74
BREAK: undefined

根据您的控制台输出 foundUser 正在返回查询,您需要执行它以便查询 运行 并获取数据。

我假设您正在使用 async/await

const foundUser = await Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec();

if (globalTest == foundUser._id) {
    console.log('match');
} else {
    console.log('no match')
}

回调版本

Auth.findById(mongoose.Types.ObjectId(globalTest)).lean().exec((err, doc) => {
    if (err) {
        console.error(err);
    }

    if (globalTest == doc._id) {
        console.log('match');
    } else {
        console.log('no match')
    }

});