MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come ottenere i nomi dagli ID in mangusta?

Devi compilare in questo modo:(è anche una buona idea escludere le password degli utenti)

 Question.find({})
    .populate("user", "-password")
    .populate("answered.user", "-password");

Inoltre ho alcuni suggerimenti sul codice:

Generalmente utilizziamo la prima lettera maiuscola e i nomi singolari per i modelli, come Utente.

utente.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;

E puoi utilizzare la seguente query per popolare gli utenti:

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);
});

Ecco un esempio di output:

[
    {
        "_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
    }
]