【问题标题】:Why can't I get the records in database after I save it in mongoDB with mongoose?为什么我用mongoose将它保存在mongoDB中后无法获取数据库中的记录?
【发布时间】:2020-06-06 02:43:51
【问题描述】:

我连接到数据库:

mongoose.connect( 'mongodb://mongo:27017/docker-node-mongo', { useNewUrlParser: true})

使用此架构:

const ItemSchema = new Schema({name: { type: String,required: true},date: {type: Date,default: Date.now}});
module.exports = Item = mongoose.model('item', ItemSchema);

我创建了 2 个要保存的 Schema 对象

const newItem1 = new Item({
    name: "Item1"
});

const newItem2 = new Item({
    name: "Item34"
});

我保存它们

Item1.save()
Item2.save()

但是当我搜索记录时;我找不到任何东西。我想它会打印一个空数组:

Item.find({}).then(result => console.log(result));
//[]

如果我再次运行程序,现在会显示记录。我需要能够在保存后找到并获取保存的数据库对象(不是在回调函数或任何东西中。)如何在保存行之后直接执行?

【问题讨论】:

    标签: node.js database mongodb mongoose save


    【解决方案1】:

    您找不到项目,因为所有函数都是异步运行的。 您应该阅读有关异步和同步的内容。

    在这种情况下将使用“异步函数”https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

    // use async function
    const main = async () => {
      const item1 = new Item({
        name: 'Item 1',
      });
    
      const item2 = new Item({
        name: 'Item 2',
      });
    
      // save item 1
      await item1.save();
    
      // save item 2 after save item 1
      await item2.save();
    
      // get all items after save item 1 and item 2
      const result = await Item.find({});
    
      console.log(result);
    };
    
    main();
    

    我们可以通过在 item 1 和 item 2 中使用异步来改进这段代码

    // use async function
    const main = async () => {
      const item1 = new Item({
        name: 'Item 1',
      });
    
      const item2 = new Item({
        name: 'Item 2',
      });
    
      // save item1 and item2 in parallel
      await Promise.resolve(item1.save, item2.save);
    
      // get all items after save item 1 and item 2
      const result = await Item.find({});
    
      console.log(result);
    };
    
    main();
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多