通过_idfindmongoose
我有一个简单的findById与mongoose的麻烦。
确认该项目存在于数据库中
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
mongoose
Story.findById(topic.storyId, function(err, res) { logger.info("res", res); assert.isNotNull(res); });
不会find它。
我也尝试转换到mongoId,仍然无法find(即使mongoose应该为你做这个)
var mid = mongoose.Types.ObjectId(storyId); let story = await Story.findOne({_id: mid}).exec();
我实际上是用这个打字稿,所以等待。
我也尝试了Story.findById(id)
方法,仍然无法find。
是否有一些简单的_id
字段查找项目? _id必须在Schema中吗? (文档说不)
我可以通过架构中的其他值find,只是_id
不能使用…
更新:我写了一个简短的testing。
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
是一个string,不确定是否会导致映射到其他表的任何问题。 我也尝试添加一些types的defs
storyId: { type: mongoose.Schema.Types.ObjectId, required: false }
因为这个查询在shell中find了doc:
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
这意味着文档中_id
的types实际上是一个string,而不是像Mongoose所期望的ObjectId
。
要使用Mongoose查找该文档,您必须在Story
的模式中将_id
定义为:
_id: { type: String }
尝试这个
Story.findOne({_id:"572b19509dac77951ab91a0b"}, function(err, story){ if (err){ console.log("errr",err); //return done(err, null); }else{ console.log(story); } });
MongoDB中的_id
不是一个string,它是一个ObjectId。 你应该做:
_id: ObjectId("572f16439c0d3ffe0bc084a4")
有关MongoDB ID的更多信息,请参见https://docs.mongodb.com/v3.0/reference/bson-types/#objectid