2016-05-20 107 views
5

我遇到了簡單的findById與貓鼬的問題。通過_id與Mongoose查找

確認該項目在DB

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

存在隨着貓鼬

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

不會找到它。

我也試圖轉換爲mongoId,仍然無法找到(即使貓鼬理應爲您完成此)

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

實際上,我試圖用打字稿使用,因此AWAIT。

我也試過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是一個字符串 不知道這會造成什麼問題映射到另一個表。 我試着也加入了一些類型DEFS

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

enter image description here

+0

_id默認情況下,沒有必要將它添加在架構 您能檢索記錄創造了更多的信息,請參閱https://docs.mongodb.com/v3.0/reference/bson-types/#objectid?如果是這樣,當使用_id嘗試將其轉換爲toObject()時。 我不確定試試看! –

回答

3

由於此查詢在外殼的DOC:

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

這意味着,文件中的_id類型實際上是一種嚴格的g,而不是像Mongoose所期待的ObjectId

爲了找到貓鼬使用該文檔,你必須在架構定義爲_idStory

_id: { type: String } 
+0

這聽起來像是正確的情況。我正在遷移一些數據,這些數據是在我們開始使用mongo之前創建的,因此這些類型可能不一致。我會試試這個,謝謝! – dcsan

-1

試試這個

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

}); 
+0

不會返回任何內容。 – dcsan

+0

任何錯誤或使用您的數據庫中存在的id正確的id –

0

MongoDB中的_id不是一個字符串,它是一個的ObjectId。你應該這樣做:

_id: ObjectId("572f16439c0d3ffe0bc084a4") 

約MongoDB的IDS

+0

這是有用的信息,但貓鼬會爲你做這個轉換。 –

+0

問題是如何將一個字符串轉換爲ObjectId,對吧? – ana06

+0

這只是關於通過_id找到一個文檔。無論如何,貓鼬會自動將它轉換爲一個ObjectId,所以你可以簡單地給它提供字符串:'_id:「572f16439c0d3ffe0bc084a4」' –