我正在尝试访问MongoDB内JSON文档正文中的Question
字段。当我运行GET请求时,得到的内容如下:
{
"_readableState": {
"objectMode": true,
"highWaterMark": 0,
"buffer": {
"head": null,
"tail": null,
"length": 0
},
"length": 0,
"pipes": null,
"pipesCount": 0,
"flowing": null,
"ended": false,
"endEmitted": false,
"reading": false,
"sync": true,
"needReadable": false,
"emittedReadable": false,
"readableListening": false,
"resumeScheduled": false,
"destroyed": false,
"defaultEncoding": "utf8",
"awaitDrain": 0,
"readingMore": false,
"decoder": null,
"encoding": null
},
"readable": true,
"domain": null,
"_events": {},
"_eventsCount": 0,
"_opts": {},
"_destroyed": false
}
我正在阅读有关JSON正文解析器的信息,但补充说这似乎行不通。这是我的index.js
:
var express = require('express')
var mongojs = require('mongojs')
var bodyParser = require("body-parser");
var app = express()
var db = require('./myDB.js')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json())
app.listen(4000, () => console.log('Hello'))
app.get('/getFlashCard', (req, res) => {
let flashID = req.body._id;
db.getFlashCard("Interview Questions", flashID, function(docs) {
console.log("Flashcard retrieved: ", docs);
res.send(docs);
});
});
这是我的myDB.js
:
getFlashCard : function(colName, flashID, callback) {
let data = mongodb.collection("Interview Questions").find({
"_id" : flashID
});
callback(data);
}
答案 0 :(得分:1)
在这里,您将返回承诺模型,而不是实际的已解决数据。
getFlashCard : async function(colName, flashID, callback) {
const data = await mongodb.collection("Interview Questions").find({_id : flashID });
callback(data);
}
答案 1 :(得分:0)
请注意,您不是在等待find
完成,而是将data
分配给mongodb.collection("").find
您需要通过使用回调(签出https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find)或使用异步/等待来等待find
完成。