저는 Node.js, 특히 Mongoose를 처음 사용합니다. 튜토리얼을 통해 배우고 있습니다. 사용자와 건물을 표시하는 훌륭하고 간단한 코드를 작성했지만 populate () 함수는 단순히 Object의 _id를 표시합니다.
내 모델 :
(...) // omitted code
var userSchema = new Schema({
login: {
type: String,
required: 'Login is required',
unique: true,
index: true,
uniqueCaseInsensitive: true
},
(...) // omitted code
,
building: {
type: Schema.Types.ObjectId,
ref: 'Building'
}
createdAt: {
type: Date,
default: Date.now
}
});
var buildingSchema = new Schema({
address: {
type: addressSchema,
index: true,
unique: true
},
planPath: String,
createdAt: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Building', buildingSchema);
module.exports = mongoose.model('User', userSchema);
내 경로 :
app.route('/api/v1/users/:userId')
.get(parkingshare.readUser);
app.route('/api/v1/buildings/:buildingId')
.get(parkingshare.readBuilding);
내 컨트롤러 :
exports.readUser = function(req, res) {
user.findById(req.params.userId, function(err, user) {
if (err)
res.send(err);
res.json(user.populate('building'));
});
};
exports.readBuilding = function(req, res) {
building.findById(req.params.buildingId, function(err, building) {
if (err)
res.send(err);
res.json(building);
});
};
다음 명령으로 데이터를 삽입했습니다.
curl --header "Content-Type: application/json" --request POST --data '{"address" : {"number":"01", "street":"test", "postCode":"01010", "city":"test"}, "planPath":""}' http://127.0.0.1:3001/api/v1/buildings
결과 :
{
"_id": "6027c85fce48810533194d08",
"address": {
"number": 1,
"street": "test",
"postCode": "01010",
"city": "test"
},
"planPath": "",
"createdAt": "2021-02-13T12:38:55.677Z",
"__v": 0
}
curl --header "Content-Type: application/json" --request POST --data '{"login":"admin","password":"admin","lastName":"","firstName":"test","building": {"_id": "6027c85fce48810533194d08"},"parkLocations":[]}' http://127.0.0.1:3001/api/v1/users
결과 :
{
"_id": "6027cab9ce48810533194d0f",
"login": "admin",
"password": "admin",
"lastName": "",
"firstName": "test",
"building": "6027c85fce48810533194d08",
"parkLocations": [],
"buildingAdmin": true,
"superAdmin": true,
"createdAt": "2021-02-13T12:42:40.908Z",
"__v": 0
}
이제 내 브라우저를 통해 populate ( 'building')있는 readUser 메서드를 통해 사용자를 얻으려고 할 때 :
여기서 채우기 ()가 작동하지 않는 이유는 무엇입니까? 혼란 스럽습니다.
단지 시도:
exports.readUser = async function (req, res) {
try {
let result = await user.findById(req.params.userId).populate("building");
res.json({ result });
} catch (err) {
res.send(err);
}
};
또는
exports.readUser = function(req, res) {
user.findById(req.params.userId).populate('building').exec(function (err, result) {
if (err) res.send(err);
res.json({ result });
})
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다