node.js 使用 Mongoose 通过 _id 查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37347802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:14:21  来源:igfitidea点击:

find by _id with Mongoose

node.jsmongodbmongoose

提问by dcsan

I am having trouble with a simple findById with mongoose.

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

Confirmed the item exists in the DB

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

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

With mongoose

与猫鼬

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

won't find it.

不会找到它。

I also tried converting to a mongoId, still cannot be found (even though mongoose supposedly does this for you)

我也尝试转换为 mongoId,但仍然找不到(即使 mongoose 应该为你做这件事)

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

I'm actually trying to use this with typescript, hence the await.

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

I also tried the Story.findById(id)method, still cannot be found.

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

Is there some gotcha to just finding items by a plain _idfield? does the _id have to be in the Schema? (docs say no)

只是在普通的_id字段中查找物品有什么问题吗?_id 必须在架构中吗?(文档说不)

I can find by other values in the Schema, just _idcan't be used...

我可以通过架构中的其他值找到,只是_id无法使用...



update: I wrote a short test for this.

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

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);
      });

    }

  });


});

It will return stuff like

它会返回类似的东西

Testing storyId 572f16439c0d3ffe0bc084a4

Testing mid 572f16439c0d3ffe0bc084a4

Testing story null

Testing no error

Testing res1 null

Testing res2 null

Testing res3 null

I noticed that topic.storyIdis a string not sure if that would cause any issues mapping to the other table. I tried also adding some type defs

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

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

enter image description here

enter image description here

采纳答案by JohnnyHK

Because this query finds the doc in the shell:

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

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

That means that the type of _idin the document is actually a string, not an ObjectIdlike Mongoose is expecting.

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

To find that doc using Mongoose, you'd have to define _idin the schema for Storyas:

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

_id: { type: String }

回答by Lawrence Edmondson

If your Mongo schema is configured to use Object Id, you query in nodeJS using

如果您的 Mongo 架构配置为使用对象 ID,则您可以使用以下命令在 nodeJS 中进行查询

models.Foo.findById(id)

models.Foo.findById(id)

where Foois your model and idis your id. here's a working example

其中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)
        } 
    })
})

In Mongo DB your query would be

在 Mongo DB 中,您的查询将是

{_id:ObjectId('5c09fb04ff03a672a26fb23a')}

回答by daymorelah

I got into this scenario too. This was how I solved it;

我也进入了这个场景。我就是这样解决的;

  • According to the mongoose documentation, you need to tell mongoose to return the raw js objects, not mongoose documents by passing the leanoption and setting it to true. e.g
  • 根据mongoose 文档,您需要通过传递lean选项并将其设置为 true来告诉 mongoose 返回原始 js 对象,而不是 mongoose 文档。例如
Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});

in your situation, it would be

在你的情况下,这将是

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

回答by Manoj Ojha

Try this

尝试这个

 Story.findOne({_id:"572b19509dac77951ab91a0b"}, function(err, story){
                if (err){
                    console.log("errr",err);
                    //return done(err, null);
                }else{
                    console.log(story);
                }

 });