비슷한 제목의 다음 질문에 대한 토론을 이미 보았습니다 mongoose 'findById' returns null with valid id 하지만 실제로 내 동일한 데이터베이스를 사용하는 다른 모든 연결이 데이터베이스 이름이 아닙니다. 같은 컬렉션이 잘 작동합니다. mongoose 4.13.6, node js 6.11 및 mongo 3.4를 사용하고 있습니다. 게시물 요청입니다. 내 findFruit를 인쇄 할 때몽구스 findById는 유효한 ID를 가지고도 null을 반환합니다
var query=req.body;
내가
var findFruit =
{
_id:query._id
}
으로 검색 매개 변수를 보내고 내가 얻을 :
이_id:'5a1cf77920701c1f0aafb85e'
이에 대한 제어 기능은 다음과 같습니다
Fruit.findById(findFruit._id,function(err,fruit){
if(_.isNull(err)){
var response = genRes.generateResponse(true,"found successfully");
callback(response);
}
else{
var response = genRes.generateResponse(false,"there occured some error : "+err);
callback(response);
}
})
나도 찾으려고 노력했다
Fruit.find(findFruit,function(err,fruit){
if(_.isNull(err)){
var response = genRes.generateResponse(true,"found successfully");
callback(response);
}
else{
var response = genRes.generateResponse(false,"there occured some error : "+err);
callback(response);
}
})
컬렉션에는 해당 ID가 있어야합니다.
나는이 자식 문제도 겪었다. https://github.com/Automattic/mongoose/issues/3079 불행히도 여러 다른 작업 기능에 영향을 줄 수 있으므로 몽구스를 다운 그레이드 할 수는 없다. 편집 : 내가 좋아하는 ObjectId가 만드는 시도 :
var mongoose = require('mongoose');
var ObjectID = require('mongodb').ObjectID;
var objectId = new ObjectID();
// Convert the object id to a hex string
var originalHex = objectId.toHexString();
// Create a new ObjectID using the createFromHexString function
var newObjectId = new ObjectID.createFromHexString(query._id);
모델 파일 :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var FruitSchema = new Schema({
name : {type : String, unique : true},
color : {type : String}
});
module.exports = mongoose.model('Fruit', FruitSchema);
여전히
'_id' 문자열에서'ObjectId'를 만들려고 했습니까? –
[nodejs를 사용하여 objectId와 mongodb의 다른 필드를 어떻게 찾을 수 있습니까?] (https://stackoverflow.com/questions/47456457/how-can-i-find-document-by-objectid-and) -one-more-field-in-mongodb-using-nodejs) – Neodan
@ Héctor 예, 어떻게 작성했는지에 대한 코드에 대한 질문에 편집을 게시했습니다. –