我在使用mongoose的findById方法时遇到了问题。
已确认数据库中存在该项。
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
使用Mongoose
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();
实际上我正在尝试使用TypeScript,因此需要加上await关键字。
我还尝试了Story.findById(id)
方法,但仍然找不到。
有没有什么技巧可以通过简单的_id
字段找到项目? 是否必须在Schema中包含_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
是一个字符串,不确定将其映射到其他表是否会导致任何问题。我还尝试添加了一些类型定义。
我注意到topic.storyId
是一个字符串,不确定将其映射到其他表是否会导致任何问题。我还尝试添加了一些类型定义。
storyId: {
type: mongoose.Schema.Types.ObjectId,
required: false
}