Mongoose와 함께 _id로 검색
몽구스가 있는 간단한 findById 때문에 어려움을 겪고 있습니다.
항목이 DB에 존재함을 확인했습니다.
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
몽구스와 함께
Story.findById(topic.storyId, function(err, res) {
logger.info("res", res);
assert.isNotNull(res);
});
찾을 수 없을 겁니다
나는 또한 mongoId로 변환하려고 시도했지만, 여전히 찾을 수 없습니다(몽구스가 당신을 위해 이것을 해준다고 해도).
var mid = mongoose.Types.ObjectId(storyId);
let story = await Story.findOne({_id: mid}).exec();
저는 실제로 이것을 타자기와 함께 사용하려고 노력하고 있습니다. 그래서 기다리고 있습니다.
저는 또한 시도했습니다.Story.findById(id)메서드, 여전히 찾을 수 없습니다.
그냥 평원에서 물건을 찾는 것에 대한 약간의 속임수가 있습니까?_id필드? _id가 스키마에 있어야 합니까?(아니오라고 대답함)
스키마의 다른 값으로 찾을 수 있습니다._id사용할 수 없습니다...
update: 저는 이것을 위해 짧은 테스트를 작성했습니다.
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다른 테이블로 매핑하는 데 문제가 발생하는지 여부를 알 수 없는 문자열입니다.나는 또한 몇 가지 유형의 def를 추가하려고 했습니다.
storyId: {
type: mongoose.Schema.Types.ObjectId,
required: false
}
이 쿼리는 셸에서 문서를 찾기 때문입니다.
db.getCollection('stories').find({_id:'572f16439c0d3ffe0bc084a4'})
즉, 유형이_id문서에는 실제로 문자열이지, 문자열이 아닙니다.ObjectId몽구스가 예상했던 것처럼.
Mongoose를 사용하여 그 문서를 찾으려면, 당신은 정의해야 합니다._id의 스키마에서.Story다음과 같이:
_id: { type: String }
Mongo 스키마가 ObjectId를 사용하도록 구성된 경우 노드에서 쿼리합니다.JS 사용
models.Foo.findById(id)
여기서 Foo는 당신의 모델이고 id는 당신의 id입니다.여기 실제 사례가 있습니다.
router.get('/:id', function(req, res, next) {
var id = req.params.id
models.Foo.findById(id)
.lean().exec(function (err, results) {
if (err) return console.error(err)
try {
console.log(results)
} catch (error) {
console.log("errror getting results")
console.log(error)
}
})
})
Mongo DB에서 당신의 질문은 다음과 같습니다.
{_id:ObjectId('5c09fb04ff03a672a26fb23a')}
한 가지 해결책은 몽구스를 사용하는 것입니다.개체 ID()
const Model = require('./model')
const mongoose = require('mongoose')
Model.find({ id: mongoose.ObjectId(userID) })
작동하지만 _id 대신 id를 사용하고 있어서 이상합니다.
이제 다음과 같은 방식으로 작업합니다.
const { mongoose } = require("mongoose");
YourModel.find({ _id: mongoose.Types.ObjectId("572f16439c0d3ffe0bc084a4") });
저도 이 시나리오에 들어갔어요.이것이 제가 해결했습니다.
- mongoose 문서에 따르면 mongoose 문서를 전달하여 mongoose 문서가 아닌 raw js 객체를 반환하도록 mongoose에게 말해야 합니다.
leantrue로 설정할 수 있습니다.예
Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
당신의 상황에서, 그것은.
Story.findById(topic.storyId, { lean: true }, function(err, res) {
logger.info("res", res);
assert.isNotNull(res);
});
_id가 기본 mongodb 키인 경우 모델에서 _id 유형을 다음과 같이 설정합니다.
_id: mongoose.SchemaTypes.ObjectId
그런 다음 mongoose를 사용하여 일반 찾기를 사용할 수 있습니다.
YourModel.find({"_id": "5f9a86b77676e180c3089c3d"});
models.findById(id)
이것을 사용해 보십시오. 참고 링크: https://www.geeksforgeeks.org/mongoose-findbyid-function/
사용해 보세요.
Story.findOne({_id:"572b19509dac77951ab91a0b"}, function(err, story){
if (err){
console.log("errr",err);
//return done(err, null);
}else{
console.log(story);
}
});
언급URL : https://stackoverflow.com/questions/37347802/find-by-id-with-mongoose
'programing' 카테고리의 다른 글
| 헤로쿠를 위한 레일즈, 몽고이드 및 유니콘 구성. (0) | 2023.06.26 |
|---|---|
| Angular 2 불투명 토큰 대 Angular 4 주입상품권 (0) | 2023.06.26 |
| 사전 보기 개체란 무엇입니까? (0) | 2023.06.26 |
| C/C++ 애플리케이션의 메모리 누수를 감지하기 위해 Mac OS X Mountain Lion 및 Mavericks에서 Valgrind를 대체할 방법이 있습니까? (0) | 2023.06.26 |
| 파이어베이스 안드로이드에서 특정 값에 대한 푸시된 ID 가져오기 (0) | 2023.06.26 |
