【问题标题】:Not getting response from mongoose model.find() query没有得到猫鼬模型的响应。find()查询
【发布时间】:2020-09-26 18:20:36
【问题描述】:

我正在尝试使用模型和模式从我的 mongo 数据库中获取所有记录。我能够连接到数据库。当我运行查询时,我没有得到任何响应。

routes.js

import express from 'express';
var router = express.Router();
import mongoose from 'mongoose';
const db = 'mongodb://localhost:27017/dbname';
import {contacts} from '../models/model.js';

// exports this js file
export { router }

//connect to mongodb

mongoose.createConnection(db, { useNewUrlParser: true , useUnifiedTopology: true }, (err, res) => {
       if(err) {
           console.error("Error: "+ err);
       }
       else {
           console.log('connected to mongodb');
       }
})


router.get('/check', (req, res)=> {
    res.send('in roues');
});

//mongo db 调用

router.get('/contacts', (req, res) => {
    console.log('getting contacts');
   let promise = contacts.find({}).exec();
   console.log(promise);
   promise.then(function(err, contacts) {
       console.log('in func');
       if(contacts) {
           console.log('data received');
           console.log(contacts);
           res.send('data received');
       }
       else {
           console.log('doc not found');
       }
   })
})

model.js

    import mongoose from 'mongoose';
    const schema = mongoose.Schema;

    const contactSchema = new schema({
            name: String,
            details: [
                {
                    text: String,
                    icon: String
                }
            ]
        });

    let contacts = mongoose.model('contacts', contactSchema);

export {contacts}

控制台输出: (节点:27440) ExperimentalWarning:ESM 模块加载器是实验性的。 服务器启动 连接到mongodb 获取联系人 承诺{}

【问题讨论】:

  • contacts.find().exec() 返回的 Promise 不接受与 contacts.find(..., nodeback) 中的 nodeback 相同的参数在 Promise 的情况下,成功传递的值将沿着 Promise 的成功路径或错误向下传递它的错误路径。分支已为您完成。因此,contacts.find({}).exec().then(successHandler).catch(errorHandler);.

标签: node.js mongodb mongoose promise


【解决方案1】:

这可能是无法捕获错误的原因。使用 then catchtry catch with async await。

  router.get('/contacts', (req, res) => {
  console.log('getting contacts');
  contacts.find({})
    .then(contacts=> {
      console.log(contacts)
    })
    .catch(error=>{
     console.log(error.mmessage)
    }

我用过 es6 的箭头函数。 你也可以关注try catch with async await

  router.get('/contacts', async(req, res) => {
    try{
     console.log('getting contacts');
     const contacts = await contacts.find({})
       console.log(contacts)
    }
    .catch(error){
     console.log(error.mmessage)
    }

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      .then(...) 只接受一个参数,即解析后的响应。

      所以,而不是 promise.then(function(err, contacts) { ... });采用 promise.then(function(contacts) { ... });

      【讨论】:

        猜你喜欢
        • 2015-10-21
        • 1970-01-01
        • 2019-06-28
        • 2013-05-19
        • 2018-12-29
        • 2018-02-05
        • 1970-01-01
        • 1970-01-01
        • 2013-02-23
        相关资源
        最近更新 更多