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
}
_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 !!! –