通过_id找到Mongoose

dcs*_*san 10 mongoose mongodb node.js

我在使用mongoose的简单findById时遇到了麻烦.

确认该项目存在于DB中

db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
Run Code Online (Sandbox Code Playgroud)

用猫鼬

  Story.findById(topic.storyId, function(err, res) {
    logger.info("res", res);
    assert.isNotNull(res);
  });
Run Code Online (Sandbox Code Playgroud)

不会找到它.

我也尝试过转换为mongoId,仍然无法找到(即使mongoose据说为你做了这个)

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

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

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

是否有些人只能通过平原_id场找到物品?_id必须在Schema中吗?(文档说不)

我可以通过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);
      });

    }

  });


});
Run Code Online (Sandbox Code Playgroud)

它将返回类似的东西

Testing storyId 572f16439c0d3ffe0bc084a4

Testing mid 572f16439c0d3ffe0bc084a4

Testing story null

Testing no error

Testing res1 null

Testing res2 null

Testing res3 null
Run Code Online (Sandbox Code Playgroud)

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

  storyId: {
    type: mongoose.Schema.Types.ObjectId,
    required: false
  }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Law*_*son 7

如果您的 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)
        } 
    })
})
Run Code Online (Sandbox Code Playgroud)

在 Mongo DB 中,您的查询将是

{_id:ObjectId('5c09fb04ff03a672a26fb23a')}
Run Code Online (Sandbox Code Playgroud)


Joh*_*yHK 6

因为此查询在shell中找到doc:

db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
Run Code Online (Sandbox Code Playgroud)

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

要使用Mongoose查找该文档,您必须_id在模式中定义Story为:

_id: { type: String }
Run Code Online (Sandbox Code Playgroud)