2016-05-20 14 views
5

Ho problemi con un findById semplice con mangusta.trova da _id con Mongoose

confermato l'elemento esiste nel DB

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

Con mangusta

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

non la troveranno.

Ho provato anche la conversione in un mongoId, ancora non può essere trovata (anche se presumibilmente mangusta fa questo per voi)

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

In realtà sto cercando di utilizzare questo con dattiloscritto, da qui l'attendono.

Ho anche provato il metodo Story.findById(id), non è ancora stato trovato.

C'è qualche trucco per trovare gli articoli semplicemente con un campo normale _id? l'_id deve essere nello schema? (Documenti non dicono)

posso trovare da altri valori nello schema, proprio _id non possono essere utilizzati ...


aggiornamento: ho scritto un breve test per questo.

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

    } 

    }); 


}); 

Si tornerà roba come

Testing storyId 572f16439c0d3ffe0bc084a4 

Testing mid 572f16439c0d3ffe0bc084a4 

Testing story null 

Testing no error 

Testing res1 null 

Testing res2 null 

Testing res3 null 

ho notato che topic.storyId è una stringa non so se questo avrebbe causato alcuna mappatura problemi per l'altra tabella. Ho provato anche aggiungere alcuni tipo defs

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

enter image description here

+0

_id predefinita, viene creato Non c'è bisogno di aggiungere che nello schema Sei in grado di recuperare i record?in tal caso, quando si utilizza that _id, provare a copiarlo in toObject(). Non sono sicuro di provarlo !!! –

risposta

3

Poiché questa query trova il documento nella shell:

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

Ciò significa che la tipo di _id nel documento è in realtà un allungamento g, non è un ObjectId come si aspetta Mongoose.

per scoprire che usando doc Mangusta, che avrebbe dovuto definire _id nello schema per Story come:

_id: { type: String } 
+0

questo suona come la situazione giusta. Sto migrando alcuni dati attraverso ciò che è stato creato prima di iniziare a usare mongo, quindi i tipi sono probabilmente incoerenti. Ci proverò, grazie! – dcsan

-1

Prova questa

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

}); 
+0

no, non restituisce nulla. – dcsan

+0

qualsiasi errore o utilizzare id id corretto che esiste nel tuo db –

0

Il _id in MongoDB non è una stringa, si tratta di un ObjectId. Si dovrebbe fare:

_id: ObjectId("572f16439c0d3ffe0bc084a4") 

Vedi https://docs.mongodb.com/v3.0/reference/bson-types/#objectid per ulteriori informazioni sugli ID MongoDB

+0

Questa è una informazione utile, ma la mangusta in realtà farà questa conversione per te. –

+0

la domanda era come convertire una stringa in ObjectId, giusto? – ana06

+0

Si tratta di trovare un documento con '_id'. In ogni caso, mangusta lo convertirà automaticamente in ObjectId in modo da poterlo semplicemente fornire con la stringa: '_id:" 572f16439c0d3ffe0bc084a4 "' –