次のように入力する必要があります:(ユーザーのパスワードを除外することもお勧めします)
Question.find({})
.populate("user", "-password")
.populate("answered.user", "-password");
また、いくつかのコードの提案があります:
通常、ユーザーなどのモデルには、最初の文字を大文字にして単数形の名前を使用します。
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;
また、次のクエリを使用してユーザーにデータを入力できます。
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);
});
出力例は次のとおりです:
[
{
"_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
}
]