Vous devez remplir comme ceci :(c'est aussi une bonne idée d'exclure les mots de passe des utilisateurs)
Question.find({})
.populate("user", "-password")
.populate("answered.user", "-password");
J'ai aussi quelques suggestions de code :
Nous utilisons généralement la première lettre en majuscule et les noms au singulier pour les modèles, comme Utilisateur.
utilisateur.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;
Et vous pouvez utiliser la requête suivante pour renseigner les utilisateurs :
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);
});
Voici un exemple de sortie :
[
{
"_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
}
]