【问题标题】:Mongoose find() 方法在我第一次运行节点时没有返回值
【发布时间】:2021-10-29 16:44:17
【问题描述】:

这个想法很简单。我在“fruitsDB”内的“fruits”集合中添加了 4 个条目。当我运行 server.js 时,它实际上将列表条目添加到数据库中。

当我检查数据库时,它说我有 4 个条目 [苹果、猕猴桃、橙子、香蕉]。但是 find 方法是

Fruit.find(function(err, fruits){
    if(err){
        console.log(err);
    } else {
        console.log(fruits);
} });

当我第一次运行 server.js 时返回一个空数组。如果我第二次运行 server.js 并检查 MongoDB 内部的集合,因为这是第二次运行新的集合内容显示如下

[苹果、猕猴桃、橙子、香蕉、苹果、猕猴桃、橙子、香蕉]

这次 find() 方法显示了数组,但只有 4 个……我在这里做错了什么?

Server.js:

const mongoose = require('mongoose');

main().catch(err => console.log(err));

// This section means connect to mongodb and create fruitsDB database inside that
async function main() {
    await mongoose.connect('mongodb://localhost:27017/fruitsDB');
  }

const fruitSchema = new mongoose.Schema({
    name: String,
    rating: Number,
    review: String
});

const Fruit = mongoose.model('Fruit', fruitSchema);

//  MongoDB will automatically pluralize the collection name
// const fruit = new Fruit({
//     name: 'Apple',
//     rating: 7,
//     review: 'Pretty solid as fruit!'
// });

// Comment out this section to prevent mongoose to 
    // save fruit to fruits collection everytime you run server.js
// fruit.save();

const peopleSchema = new mongoose.Schema({
    name: String,
    age: Number
});

const People = mongoose.model('People', peopleSchema);

const people = new People({
    name: 'John',
    age: 37
});

people.save();

const apple = new Fruit({
    name: 'Apple',
    rating: 7,
    review: 'Pretty solid as fruit!'
});

const kiwi = new Fruit({
    name: 'Kiwi',
    rating: 10,
    review: 'The best fruit!'
});

const orange = new Fruit({
    name: 'Orange',
    rating: 4,
    review: 'Too sour for me!'
});

const banana = new Fruit({
    name: 'Banana',
    rating: 3,
    review: 'Weird texture!'
});

Fruit.insertMany([apple, kiwi, orange, banana], function(error){
    if(error){
        console.log(error);
    } else {
        console.log('New entries are added to the database!');
    }
});

// Read the fruits collection
Fruit.find(function(err, fruits){
    if(err){
        console.log(err);
    } else {
        console.log(fruits);
    }
});

【问题讨论】:

    标签: javascript node.js mongodb mongoose methods


    【解决方案1】:

    您必须等待 Mongoose 连接到您的 MongoDB 服务器,然后您应该执行所有逻辑。您可以做的只是将所有逻辑放在main() 函数中await mongoose.connect('mongodb://localhost:27017/fruitsDB'); 之后。这将确保 Mongoose 在执行任何数据库查询之前连接到 MongoDB 服务器。

    const mongoose = require('mongoose');
    
    main().catch(err => console.log(err));
    
    // This section means connect to mongodb and create fruitsDB database inside that
    async function main() {
      await mongoose.connect('mongodb://localhost:27017/fruitsDB');
    
      const fruitSchema = new mongoose.Schema({
        name: String,
        rating: Number,
        review: String
      });
    
      const Fruit = mongoose.model('Fruit', fruitSchema);
    
      //  MongoDB will automatically pluralize the collection name
      // const fruit = new Fruit({
      //     name: 'Apple',
      //     rating: 7,
      //     review: 'Pretty solid as fruit!'
      // });
    
      // Comment out this section to prevent mongoose to 
      // save fruit to fruits collection everytime you run server.js
      // fruit.save();
    
      const peopleSchema = new mongoose.Schema({
        name: String,
        age: Number
      });
    
      const People = mongoose.model('People', peopleSchema);
    
      const people = new People({
        name: 'John',
        age: 37
      });
    
      people.save();
    
      const apple = new Fruit({
        name: 'Apple',
        rating: 7,
        review: 'Pretty solid as fruit!'
      });
    
      const kiwi = new Fruit({
        name: 'Kiwi',
        rating: 10,
        review: 'The best fruit!'
      });
    
      const orange = new Fruit({
        name: 'Orange',
        rating: 4,
        review: 'Too sour for me!'
      });
    
      const banana = new Fruit({
        name: 'Banana',
        rating: 3,
        review: 'Weird texture!'
      });
    
      Fruit.insertMany([apple, kiwi, orange, banana], function(error) {
        if (error) {
          console.log(error);
        } else {
          console.log('New entries are added to the database!');
        }
      });
    
      // Read the fruits collection
      Fruit.find(function(err, fruits) {
        if (err) {
          console.log(err);
        } else {
          console.log(fruits);
        }
      });
    }
    

    【讨论】:

      【解决方案2】:

      find() 方法在数据库有机会存储数据之前运行。
      您可以使用 awaitinsertMany() 调用存储在 async 函数中,然后将 Fruit.find()之后

      async function myFunc() {
          await Fruit.insertMany([apple, kiwi, orange, banana], function (error) {
              if (error) {
                  console.log(error);
              } else {
                  console.log('New entries are added to the database!');
              }
          });
          Fruit.find(function (err, fruits) {
              if (err) {
                  console.log(err);
              } else {
                  console.log(fruits);
              }
          });
      }
      myFunc();
      

      或者利用 Promise 回调并使用 .then()

      myFunc().then(() => {
          Fruit.find(function (err, fruits) {
              if (err) {
                  console.log(err);
              } else {
                  console.log(fruits);
              }
          });
      },err=> console.log(err));
      

      【讨论】:

      • 这仍然不起作用。我不确定缺少什么,因为我的异步等待功能很难理解。
      猜你喜欢
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多