Get object ID inside array Mongodb Nodejs REST API

uidvcgyl  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(154)

我已经用nodejs和mongodb atlas创建了一个rest API。
我有一个对象数组,每个对象都有一个id,我想通过id得到这些对象


的数据

exports.GetUserInfo = (req , res  , next)=>{
Client.find({ReadingHistory: 
mongoose.Schema.ObjectId("5e557c8f0fda580b28866b9f")})
.select()
.exec()
.then(doc=>{        
    if (doc) {
        console.log('from the database',doc);
    } else {
        console.log('invalid ID')
    }

        if (doc) {
            res.status(200).json({
                ReadingHistory: doc,

            });  
        } else {
            res.status(404).json({message: 'Sorry... no data'})
        }

  })
     .catch(err =>{ 
        console.log(err);
        res.status(500).json({error: err})
     });
}

}

字符串

8aqjt8rx

8aqjt8rx1#

MongoDB中的ObjectId不能用=或!==进行比较,我们必须使用ObjectId.prototype.equals。因此,您可以编写以下代码:

function find(id) {
  return resultArray.find(obj => obj._id.equals(id));
}

字符串
完整的伪代码可能是:

exports.GetUserInfo = (req , res , next) => {
  const conditions = {id: req.params.clientId};
  const result = Client.find(conditions); // suppose Client.find() returns the query result from mongodb.
  return result.ReadingHistory.find(Obj => obj._id.equals(conditions));
}

相关问题