【问题标题】:MognoDB Nodejs getting specific collection documents by IDMongoDB Node Js通过ID获取特定集合文档
【发布时间】:2021-07-26 03:39:27
【问题描述】:

我正在尝试从节点中的数据库中获取特定的集合文档。我似乎正在检索我的“照片”集合中的整个文档列表。我已经玩过几次了,想知道是否有更简单/更好的方法来获取数据,而不是我正在尝试做的事情。我要做的就是获取一张带有特定 ID 的照片,然后将该照片返回给用户。

这是我的代码:

async function getPhoto(id) {

  const db = getDbReference();
  const collection = db.collection("photos")
  console.log({"id": id})
  
  const results = await collection
  .findOne(id)
  .toArray();
  return results
  
}

exports.getPhoto = getPhoto;

照片端点文件:

router.get('/:photoID', async (req, res, next) => {
  // const photoID = parseInt(req.params.photoID);
  
  try {
    const photo = await getPhoto(req.params.photoID)
    res.status(201).send(photo);


  }catch(err){
    console.error("--error", err);
    res.status(500).send({
      err: "Error fetching photo from DB. Try again later",
    });

【问题讨论】:

    标签: node.js database mongodb


    【解决方案1】:

    尝试使用find 而不是findOne

    ObjectID = require('mongodb').ObjectID
    
    async function getPhoto(id) {
    
      const db = getDbReference();
      const collection = db.collection("photos")
      console.log({"id": id})
      
      const results = await collection.find({_id: new ObjectID(id)}).toArray();
      return results
    }
    

    建议:您应该检查mongoose 包以与mongoDB 交互。它将简化您的查询,并允许您创建一个直接映射到您的集合的模式模型。

    包裹:https://www.npmjs.com/package/mongoose

    【讨论】:

    • 现在我只是得到一个空数组,就像它几乎没有找到任何具有该 ID 的东西。这是我的邮递员电话:localhost:8000/photos/60903398deba3d377ca907d2,这是我在 Mongo DB 中的对象 { "_id" : ObjectId("60903398deba3d377ca907d2"), "userid" : 2, "businessid" : 1, "caption" : "这很奇怪photo" } 另外,我会检查 Mongoose
    • localhost。只有你可以打开它。
    • 是的。奇怪的是我得到一个空数组但状态为 201
    • 我更新了我的答案。您可能需要发送 ObjectId() 而不是字符串。你能再试一次吗?
    • 我得到一个参考错误 ObjectId is not defined
    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2021-03-02
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多