【问题标题】:The save() function on mongoose doesn't workmongoose 上的 save() 函数不起作用
【发布时间】:2021-01-22 00:46:38
【问题描述】:

我正在尝试使用 mongoose 在 mongodb 上保存一个新文档,但似乎链接 .save() 行没有被执行。不知道我做错了什么。 这是我的代码:

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('\nAnswer: ');
  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.');
  };
};

这是我的 CMD:

当我执行它时,只有函数保存之前和之后的 console.logs 会显示在 CMD 中。我也没有收到任何错误消息。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    这里有几个问题。

    1. mongoose.connect 是异步的,在开始循环之前您无需等待连接。您可以通过将其余代码放在 .then 回调中来解决此问题。
    2. .save 也是异步的,但异步代码在 while 循环中无法按预期工作。循环的下一次迭代在 .save 完成执行之前开始。处理这种情况的一种方法是将代码放入一个调用自身的函数中(称为recursive function

    我已经在下面更新的代码中标记了 cmets 中的点:

    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('\nAnswer: ');
          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);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多