javascript - 如何在猫鼬中查询服务器的启动?
问题描述
开始.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}`)
})
解决方案
您可以添加一个回调,该回调将在 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({ })
推荐阅读
- javascript - 如何有条件地更改 vue.js 附加外部
- spring - 如何使用spring webflux实现跟踪服务到服务?
- c# - 在 .NET 5 中生成 Microsoft Fakes 程序集
- python - 如何在程序不停止的情况下使用异常?
- css - 将 CSS Grid 内容从一列移动到另一列
- linux - 无法根据 java 程序的结果运行脚本
- twincat - IEC61131-3中功能块调用的区别
- javascript - AR.js 全景图中的标记问题
- c# - EF Core 连接结果的通用类型类
- javascript - 范围日期的 Flatpicker 最小天数