Сохранение пользователя из userSchema на questionSchema в качестве вложенного документа для последующего доступа к пользовательским данным - PullRequest
0 голосов
/ 20 мая 2019

Мое приложение позволит пользователям задавать вопросы, мне нужно сохранить пользовательские данные в QuestionSchema, чтобы позже отобразить данные, могу ли я сохранить пользователя, а также теги, как вложенный документ на QuestionSchema со всеми его данными для доступа позже от вопроса щема? Будет ли он создавать новый _id для вложенного документа или он сохранит пользователя _id, который я хочу, если передам его при создании нового вопроса?

questionSchema

const mongoose = require("mongoose");
const tagSchema = require("./tag.schema.js");
const userSchema = require("./user.schema.js");

// Schema variable
const Schema = mongoose.Schema;


const questionSchema = new Schema({

    _id: mongoose.Schema.Types.ObjectId,
    user: {
        type: userSchema,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    tags: {
        type: [tagSchema],
        required: true
    },
    upVotes: {
        type: Number,
        default: 0
    },
    downVotes: {
        type: Number,
        default: 0
    },
    date: {
        type: Date,
        required: true,
        default: Date.now
    },
});

// Create model
const Question = mongoose.model('Question', questionSchema);

// Export model
module.exports = Question;

userSchema

const mongoose = require("mongoose");
const mongooseUniqueValidator = require("mongoose-unique-validator");
const trophySchema = require("./trophy.schema.js");

// Schema variable
const Schema = mongoose.Schema;

// Users
const userSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    username: {
        type: String,
        unique: true,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    profilePic: {
        type: String,
        default: "http://i.imgur.com/AItCxSs.jpg"
    },
    upVotes: {
        type: Number,
        default: 0
    },
    downVotes: {
        type: Number,
        default: 0
    },
    experience: {
        type: Number,
        default: 0
    }
    trophies: [trophySchema]
});

userSchema.plugin(mongooseUniqueValidator);

// Create model
const User = mongoose.model('User', userSchema);

// Export model
module.exports = User;

...