【问题标题】:mongoose returns empty array (i tried whatever i could)猫鼬返回空数组(我尽我所能)
【发布时间】:2021-02-23 02:35:12
【问题描述】:

架构:文件名:Login.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const LoginSchema = new Schema({
  uname: {
    type: String,
    required: true
  },
  pass: {
    type: String,
    required: true
  }
});

module.exports = Login = mongoose.model('login', LoginSchema);

index.js 文件:

const express = require('express');
const mongoose = require('mongoose');

const app = express();

// Connect to MongoDB
mongoose
  .connect(
    'mongodb://mongo:27017/docker-node-mongo',
    { useNewUrlParser: true }
  )
  .then(() => console.log('MongoDB Connected'))
  .catch(err => console.log(err));
  
const Login = require('./models/Login');

app.post('/',(req,res) => {
    
    
        const newLogin = new Login({
            uname: req.body.uname,
            pass: req.body.pass
          });
        console.log(newLogin);
        newLogin.save();

    Login.find({},function (err, logins) {
        if (err) return console.error(err);
        console.log("cool: ",logins);
      });
    res.redirect('/main');
});

以下是控制台中的输出: MongoDB 已连接

{ _id: 5fab21a3931694001290326e, uname: 'guest', pass: 'guest' }

酷:[]


.find() 的输出为空。并且就在我输入一个条目之前,该条目甚至显示在控制台中。我看到了复数的东西,但它不起作用。

请帮忙。

【问题讨论】:

    标签: javascript html mongodb mongoose mongodb-query


    【解决方案1】:

    Mongodb save() 是异步的,所以它不会等待文档的保存。当它尝试查找文档时,由于尚未保存,因此无法找到它。您可以使用 async/await 等待保存过程然后继续。

    app.post('/', async (req,res) => {
            
                const newLogin = new Login({
                    uname: req.body.uname,
                    pass: req.body.pass
                  });
                console.log(newLogin);
                await newLogin.save();
        
            Login.find({},function (err, logins) {
                if (err) return console.error(err);
                console.log("cool: ",logins);
              });
            res.redirect('/main');
        });
    

    【讨论】:

    • 谢谢我还有一个问题:在架构中,我想将预定义的用户名和密码硬编码为来宾,来宾。这个怎么做??谢谢
    • 您可以在架构中使用默认值。例如默认值:“Guest”
    猜你喜欢
    • 1970-01-01
    • 2016-04-28
    • 2017-03-30
    • 2019-07-17
    • 2018-08-28
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多