Anda perlu mengisi seperti ini:( juga merupakan ide bagus untuk mengecualikan kata sandi pengguna)
Question.find({})
.populate("user", "-password")
.populate("answered.user", "-password");
Saya juga punya beberapa saran kode:
Kami biasanya menggunakan huruf pertama dengan huruf besar dan nama tunggal untuk model, seperti Pengguna.
pengguna.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;
Dan Anda dapat menggunakan kueri berikut untuk mengisi pengguna:
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);
});
Berikut adalah contoh keluarannya:
[
{
"_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
}
]