[英]How do I extract the body out of the MongoDB Document from my get request?
I am trying to access the Question
field in the body of a JSON document inside a MongoDB.我正在尝试访问 MongoDB 内的 JSON 文档正文中的
Question
字段。 When I run the GET request I get something that looks like this:当我运行 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
}
I was reading about JSON body parsers but adding that does not seem to be working.我正在阅读有关 JSON 正文解析器的信息,但补充说这似乎不起作用。 Here is my
index.js
:这是我的
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);
});
});
Here is my myDB.js
:这是我的
myDB.js
:
getFlashCard : function(colName, flashID, callback) {
let data = mongodb.collection("Interview Questions").find({
"_id" : flashID
});
callback(data);
}
here you are returning the promise model instead of the actual resolved data.在这里,您将返回 promise model 而不是实际解析的数据。
getFlashCard : async function(colName, flashID, callback) {
const data = await mongodb.collection("Interview Questions").find({_id : flashID });
callback(data);
}
Notice that you are not waiting for the find
to finish, instead you are assigning data
to mongodb.collection("").find
请注意,您不是在等待
find
完成,而是将data
分配给mongodb.collection("").find
You need to wait for find
to finish by either using a callback (check out https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find ) or by using async/await.您需要通过使用回调(查看https://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find )或使用 async/await 来等待
find
完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.