Сохранение массива объектов - mongoDB - PullRequest
0 голосов
/ 03 августа 2020

Я пытаюсь хранить документы в mongoDB из объектов в массиве. Массив содержит JSON объектов, которые соответствуют определенному шаблону RegEx в обычном / текстовом файле. Но такие методы, как save () или insert (), insertMany () или create (), не работают должным образом. Кажется, проблема в строке после For L oop. Есть ли какой-нибудь способ решить эту проблему?

Это мой код для обработки запроса:

routerDocx.post('/docx', upload.single('docx'), function(req,res,next){
    let filePath = req.file.path
    let data = fs.readFileSync(filePath, 'utf8')
    let topic = data.match(/Topic\:\s(.*)\r\n/m)
    let matchAll = data.matchAll(/[0-9]\)\s(.*)\r\n[A-Z]\)(.*)\r\n[A-Z]\)(.*)\r\n[A-Z]\)(.*)\r\n[A-Z]\)(.*)\r\n[A-Z]\)(.*)\r\n(.*)\r\n/g)
    matchAll = Array.from(matchAll)
    let ques = matchAll[0]
    console.log(ques[0])
    console.log("Topic: "+topic[1])
    let quesArray = new Array()
    
    for(let i = 0; i < matchAll.length; i++){
        let ques = matchAll[i]
        var testQuestion =  new TestQuestions({
            topic: topic[1],
            question: ques[1],
            option1: ques[2],
            option2: ques[3],
            option3: ques[4],
            option4: ques[5],
            option5: ques[6],
            answer: ques[7]
        })
        quesArray.push(testQuestion)
    }
    **TestQuestions.insertMany(quesArray)**
});

Это моя схема mon goose: (TestQuestion)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

//create TestQuestions Schema & Models
const testQuestionsSchema = new  Schema({
    createdBy: {type: mongoose.Schema.Types.ObjectId, ref: 'College'},
    topic: String,
    question: String,
    option1: String,
    option2: String,
    option3: String,
    option4: String,
    option5: String,
    answer: String
})

module.exports = mongoose.model('TestQuestions', testQuestionsSchema);

Заранее спасибо ..!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...