There are a couple of problems here.
mongoose.connect
is asynchronous and you aren't waiting for the connection before you start your loop. You can fix that by putting the rest of the code in the .then
callback.
.save
is also asynchronous, but asynchronous code doesn't work as expected in a while loop. The next iteration of the loop started before .save finished executing. One way to handle that is to put the code in a function that calls itself (called a recursive function)
I've marked the points in comments in the updated code below:
const rlSync = require('readline-sync');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/desafio_22012021', {useNewUrlParser: true, useUnifiedTopology: true}).then(() =>
{
///////////////////////////////
// #1 Put all this code inside the .then of mongoose.connect so it will wait
//////////////////////////////
console.log('DB connected');
var option;
// model student
const studentSchema = mongoose.Schema({
_id: {
type: Number,
require: true
},
nameStudent: {
type: String,
require: true
},
idCourse: {
type: Array
}
});
const newStudent = mongoose.model('alunos', studentSchema);
// setTimeout(menu, 1000);
///////////////////////////////
// #2 Recursive function (instead of the while loop)
//////////////////////////////
function waitForInput(option) {
option = rlSync.question('
Answer: ');
option = parseInt(option, 10);
switch (option) {
case 0:
// Not sure what you want to happen here but you can add waitForInput() to wait for input again or put process.exit(0) to stop the program
break;
case 1:
console.log('Befora save');
var documento = new newStudent({_id: 11, nameStudent: "Juliana", idCourse: [1,2]});
documento.save((err, doc) => {
if (err) {
console.log(err);
process.exit(0);
} else {
console.log('Ok')
}
console.log('After save');
// Function calls itself to wait for next input
waitForInput()
});
break;
default:
console.log('Invalid option.');
};
}
// Start waiting for the user input
waitForInput();
}).catch((err) =>{
console.log(err);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…