как определить схему mongodb и как написать метод post на следующем экране - PullRequest
0 голосов
/ 01 октября 2019

Я пытаюсь добавить несколько вопросов с несколькими ответами, но не могу сохранить их в MongoDB, я хочу, чтобы каждый вопрос был сохранен как один объект. с уникальным object_id

i attached an image which is related to the question


  [1]: https://i.stack.imgur.com/ggnmU.jpg

Ответы [ 2 ]

0 голосов
/ 03 октября 2019
const mongoose = require("mongoose");
const Schema = mongoose.Schema;


const questionSchema = new mongoose.Schema({

questionType: {
        type: Schema.Types.ObjectId,
        ref:"questionType",
        required: true
},

questionTitle: {
    type: String,
    required: true
},


question: {
    type: String,
    required: true
},

answer: {
    type: Array,
    required: true
},

createdBy: {
    type: String,
    required: true
},



}, {versionKey: false, timestamps: true});

module.exports = mongoose.model("question", questionSchema);
0 голосов
/ 03 октября 2019
var async = require("async");

exports.createQuestions = (req,res) => {
   let ress=[];
   async.each(req.body,function(item,callback)
   { 
    const questions = new Questions(item);
    Questions.find({questionTitle:item.questionTitle},function(err,data){
           if(err){
               console.log(err);
           }
          else if(data.length>0){
               ress.push( {
                   'message':item.questionTitle+'is already existed'
                });
                callback();
            }
           else if(data.length==0){
            questions.save().then(result => {
            ress.push({
           "message": "added successfully",
           "status":200,
           "data":result})
           console.log('result',ress)
           callback();
            });
        }
    })   
   },
   function(err) {
    console.log('iterating done',err);
    return res.json({"result":ress});
})
};
...