首页 > 解决方案 > 如何在猫鼬中查询服务器的启动?

问题描述

开始.js:

const express = require('express')
const app = express()
const port = 3000

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser: true}); //to connect with mongodb..not exact code I used but this

现在假设我在 mongodb 中存储了一些数据....在模型书中存储的 Books 集合中

我调用模型并从中获取:

const bookdetails = Books.find({ }).exec()

我试过了 :

var respo;
bookdetails.then(function(result) {
    console.log(result) //gives the value stored in bookdetails
    respo = result; 
})
console.log(respo) //...but value not stored in here...it gives undefined

但是它提供了 console.log(bookdetails) ...... Promise { }而不是存储在图书集合中的所有数据。如何在服务器启动时获取数据....如果我通过路由使用或调用 api 它工作得很好

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

标签: javascriptnode.jsexpress

解决方案


您可以添加一个回调,该回调将在 promise 解决后执行,或者使用 async/await

let bookDetails ;
Books.find()
  .exec(function (err, book) {
  if(err)
    throw new Error(err)
  else
    bookDetails = book
});

或者

const bookdetails = await Books.find({ })

推荐阅读