gpt4 book ai didi

node.js - MongoDb find() 返回大量不需要的字段

转载 作者:太空宇宙 更新时间:2023-11-03 22:44:07 24 4
gpt4 key购买 nike

 app.get('/',function(req,res){
var response={};
db.collection('first').find({},function(err,result){
if(err){
db.close();
console.log('Error');
console.log(err);
}
else{
db.close();
console.log('Success');
console.log(response);
}
});

res.end(response);
});

但是,这会返回大量不需要的数据。我也查看了这些数据,但我没有看到集合中的条目值/字段。我希望它仅以 JSON 对象的形式返回字段值。我该怎么做?

示例输出:(太多,无法发布所有内容)

Readable {
connection: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: '****',
cmd:
{ find: '******',
limit: 0,
skip: 0,
query: {},
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter],
options: [Getter],
native_parser: [Getter],
slaveOk: [Getter],
writeConcern: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object] },
_eventsCount: 5,
_maxListeners: undefined,

还有更多……

谢谢。

最佳答案

首先,您正在记录并发回一个空的 response 对象。您的问题来自语法, find()仅接受一个参数并返回一个游标,您必须在循环内调用 next() 来获取每个文档,或者调用 toArray() 一次获取所有文档:

app.get('/', function (req, res) {
db.collection('first').find({}).toArray(function (err, docs) {
db.close();

if (err) {
console.log('Error');
console.log(err);
res.end();
}
else {
console.log('Success');
console.log(docs);
res.json(docs);
}
});
});

关于node.js - MongoDb find() 返回大量不需要的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com