Musíte vyplnit takto:(také je dobré vyloučit uživatelská hesla)
Question.find({})
.populate("user", "-password")
.populate("answered.user", "-password");
Také mám několik návrhů kódu:
U modelů obecně používáme první písmeno velké a jednotné číslo, například User.
user.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
question.js
const mongoose = require("mongoose");
const QuestionSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
question: {
type: String
},
name: {
type: String
},
answered: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
}
]
});
const Question = mongoose.model("Question", QuestionSchema);
module.exports = Question;
A k naplnění uživatelů můžete použít následující dotaz:
const Question = require("../models/question");
router.get("/question", async (req, res) => {
const questions = await Question.find({})
.populate("user", "-password")
.populate("answered.user", "-password");
res.send(questions);
});
Zde je ukázkový výstup:
[
{
"_id": "5dc12a6aa875cd0ca8b871eb",
"user": {
"_id": "5dc129eda875cd0ca8b871e8",
"name": "user 1",
"email": "[email protected]",
"date": "2019-11-05T07:51:09.625Z",
"__v": 0
},
"question": "question 1",
"name": "question 1 name",
"answered": [
{
"_id": "5dc12a6aa875cd0ca8b871ed",
"user": {
"_id": "5dc12a00a875cd0ca8b871e9",
"name": "user 2",
"email": "[email protected]",
"date": "2019-11-05T07:51:28.892Z",
"__v": 0
}
},
{
"_id": "5dc12a6aa875cd0ca8b871ec",
"user": {
"_id": "5dc12a0aa875cd0ca8b871ea",
"name": "user 3",
"email": "[email protected]",
"date": "2019-11-05T07:51:38.060Z",
"__v": 0
}
}
],
"__v": 0
}
]