I've run into a problem that simple mongodb/monk find() doesn't work. I know find() returns promise and all 3 ways to resolve it doesn't work. What am I doing wrong? Thanks!
This is my code. All of 3 routes doesn't return at all and need to be canceled:
const express = require('express');
const router = express.Router();
const db = require('monk')('mongodb://127.0.0.1:27017/storage');
const files = db.get('fs.files');
router.get('/1', async (req, res) => {
const result = await files.find();
res.json(result);
});
router.get('/2', (req, res) => {
files.find()
.then(
(result) => { res.json(result) },
(error) => { res.json(error) }
);
});
router.get('/3', (req, res) => {
files.find({}, (result) => {
res.json(result)
});
});
module.exports = router;
UPDATE: I've got rid of munk and native MongoDB driver does the job:
router.get('/', (req, res) => {
mongo.MongoClient.connect(mongo_uri, mongoClientOptions, async (err, conn) => {
assert.ifError(err);
const files = await conn.db('storage')
.collection('fs.files')
.find()
.toArray();
res.json(files);
});
});
Problem was I failed to check if munk connection manager returned proper db instance.
Solution: Change db.get('fs.files'); to db.get('files');
This is my demo project -> database: demo, collections: users
const express = require('express');
const app = express();
const db = require('monk')('mongodb://127.0.0.1:27017/demo');
const files = db.get('users');
app.get('/1', async (req, res) => {
const result = await files.find();
res.json(result);
});
app.get('/2', (req, res) => {
files.find()
.then(
(result) => { res.json(result) },
(error) => { res.json(error) }
);
});
app.get('/3', (req, res) => {
files.find({}, (result) => {
res.json(result)
});
});
app.listen(4000, () => {
console.log('Example app listening at 4000')
})
module.exports = app;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.