使用 Mongoose 通过 _id 查找

新手上路,请多包涵

我在使用猫鼬的简单 findById 时遇到了麻烦。

确认该项目存在于数据库中

db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})

与猫鼬

  Story.findById(topic.storyId, function(err, res) {
    logger.info("res", res);
    assert.isNotNull(res);
  });

不会找到它。

我还尝试转换为 mongoId,但仍然找不到(即使据说 mongoose 会为您执行此操作)

 var mid = mongoose.Types.ObjectId(storyId);
let story = await Story.findOne({_id: mid}).exec();

我实际上正在尝试将它与打字稿一起使用,因此等待。

我也试过 Story.findById(id) 方法,还是找不到。

仅通过简单的 _id 字段查找项目是否有一些问题? _id 必须在模式中吗? (文档说不)

我可以通过Schema中的其他值找到,只是 _id 不能使用…


更新:我为此写了一个简短的测试。

 describe("StoryConvert", function() {

  it("should read a list of topics", async function test() {
    let topics = await Topic.find({});

    for (let i = 0; i < topics.length; i ++) {
      let topic = topics[i];
    // topics.forEach( async function(topic) {
      let storyId = topic.storyId;
      let mid = mongoose.Types.ObjectId(storyId);
      let story = await Story.findOne({_id: mid});
      // let story = await Story.findById(topic.storyId).exec();
      // assert.equal(topic.storyId, story._id);
      logger.info("storyId", storyId);
      logger.info("mid", mid);
      logger.info("story", story);
      Story.findOne({_id: storyId}, function(err, res) {
        if (err) {
          logger.error(err);
        } else {
          logger.info("no error");
        }
        logger.info("res1", res);
      });

      Story.findOne({_id: mid}, function(err, res) {
        logger.info("res2", res);
      });

      Story.findById(mid, function(err, res) {
        logger.info("res3", res);
        // assert.isNotNull(res);
      });

    }

  });

});

它会返回类似的东西

Testing storyId 572f16439c0d3ffe0bc084a4

Testing mid 572f16439c0d3ffe0bc084a4

Testing story null

Testing no error

Testing res1 null

Testing res2 null

Testing res3 null

我注意到 topic.storyId 是一个字符串,不确定这是否会导致映射到另一个表的任何问题。我也尝试添加一些类型定义

  storyId: {
    type: mongoose.Schema.Types.ObjectId,
    required: false
  }

在此处输入图像描述

原文由 dcsan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 864
2 个回答

因为这个查询在 shell 中找到了文档:

 db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})

这意味着文档中 _id 的类型实际上是一个字符串,而不是像 Mongoose 期望的那样的 ObjectId

要使用 Mongoose 查找该文档,您必须在 _id Story 为:

 _id: { type: String }

原文由 JohnnyHK 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您的 Mongo 架构配置为使用对象 ID,则您可以在 nodeJS 中使用

models.Foo.findById(id)

其中 Foo 是您的模型, id 是您的 ID。这是一个工作示例

router.get('/:id', function(req, res, next) {
    var id = req.params.id
    models.Foo.findById(id)
        .lean().exec(function (err, results) {
        if (err) return console.error(err)
        try {
            console.log(results)
        } catch (error) {
            console.log("errror getting results")
            console.log(error)
        }
    })
})

在 Mongo DB 中,您的查询将是

{_id:ObjectId('5c09fb04ff03a672a26fb23a')}

原文由 Lawrence Edmondson 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题