我在使用猫鼬的简单 findById 时遇到了麻烦。
确认该项目存在于数据库中
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
与猫鼬
Story.findById(topic.storyId, function(err, res) {
logger.info("res", res);
assert.isNotNull(res);
});
不会找到它。
我还尝试转换为 mongoId,但仍然找不到(即使据说 mongoose 会为您执行此操作)
var mid = mongoose.Types.ObjectId(storyId);
let story = await Story.findOne({_id: mid}).exec();
我实际上正在尝试将它与打字稿一起使用,因此等待。
我也试过 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
是一个字符串,不确定这是否会导致映射到另一个表的任何问题。我也尝试添加一些类型定义
storyId: {
type: mongoose.Schema.Types.ObjectId,
required: false
}
原文由 dcsan 发布,翻译遵循 CC BY-SA 4.0 许可协议
因为这个查询在 shell 中找到了文档:
这意味着文档中
_id
的类型实际上是一个字符串,而不是像 Mongoose 期望的那样的ObjectId
。要使用 Mongoose 查找该文档,您必须在
_id
Story
为: