通过_id与猫鼬一起找到 [英] find by _id with Mongoose
问题描述
我遇到了一个带有猫鼬的简单findById的麻烦.
I am having trouble with a simple findById with mongoose.
确认该项目存在于数据库中
Confirmed the item exists in the DB
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
有猫鼬
Story.findById(topic.storyId, function(err, res) {
logger.info("res", res);
assert.isNotNull(res);
});
找不到它.
我还尝试了转换为mongoId,但仍然找不到(即使猫鼬据说可以为您完成此操作)
I also tried converting to a mongoId, still cannot be found (even though mongoose supposedly does this for you)
var mid = mongoose.Types.ObjectId(storyId);
let story = await Story.findOne({_id: mid}).exec();
我实际上正在尝试将其与打字稿一起使用,因此正在等待.
I'm actually trying to use this with typescript, hence the await.
我也尝试了Story.findById(id)
方法,但仍然找不到.
I also tried the Story.findById(id)
method, still cannot be found.
是否有一些陷阱只能通过简单的_id
字段查找项目?
_id是否必须在模式中? (文档说不)
Is there some gotcha to just finding items by a plain _id
field?
does the _id have to be in the Schema? (docs say no)
我可以通过Schema中的其他值找到,只是不能使用_id
...
I can find by other values in the Schema, just _id
can't be used...
更新:为此我写了一个简短的测试.
update: I wrote a short test for this.
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
是一个字符串
不知道这是否会导致映射到其他表的任何问题.
我也尝试添加一些类型defs
I noticed that topic.storyId
is a string
not sure if that would cause any issues mapping to the other table.
I tried also adding some type defs
storyId: {
type: mongoose.Schema.Types.ObjectId,
required: false
}
推荐答案
因为此查询在外壳中找到了文档,所以:
Because this query finds the doc in the shell:
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
这意味着文档中_id
的类型实际上是字符串,而不是Mongoose期望的ObjectId
.
That means that the type of _id
in the document is actually a string, not an ObjectId
like Mongoose is expecting.
要使用Mongoose查找该文档,您必须在Story
的架构中将_id
定义为:
To find that doc using Mongoose, you'd have to define _id
in the schema for Story
as:
_id: { type: String }
这篇关于通过_id与猫鼬一起找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!