Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

javascript - The save() function on mongoose doesn't work

I'm trying to save a new doc on mongodb with mongoose but it seems link the .save() line doesn't get executed. Not sure what I'm doing wrong. This is my code:

const rlSync = require('readline-sync');

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/desafio_22012021', {useNewUrlParser: true, useUnifiedTopology: true}).then(() => 
  {
    console.log('DB connected');
  }).catch((err) =>{
    console.log(err);
  });

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

while (option != 0) {
  option = rlSync.question('
Answer: ');
  option = parseInt(option, 10);

  switch (option) {
    case 0:
      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('During save');
      });
      console.log('After save');
      
      break;

    default:
      console.log('Invalid option.');
  };
};

This is my CMD:

enter image description here

When I execute it only the console.logs before and after the function save show up in the CMD. I don't get any error messages either.

question from:https://stackoverflow.com/questions/65837852/the-save-function-on-mongoose-doesnt-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of problems here.

  1. 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.
  2. .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);
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...