如何返回mongodb集合中的所有文档



我是javascript和mongodb的新手,我正在尝试构建一个简单的博客引擎。我正试图返回mongodb中的所有博客文章,以便使用这些数据来填充ejs模板。我用console.log得到了我想要的输出,但当我尝试将函数结果保存到变量时,我得到的数据比我需要的多得多。

这是代码:

mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title : String,
image: String,
body: String
});
const Model = mongoose.model;
const BlogPost = new Model('posts', BlogSchema);
BlogPost.find((err, posts) => {
console.log(posts);
});

这将在日志中生成我想要的内容:

[
{
_id: new ObjectId("62ef1ea68a82d65948539324"),
title: 'Test Title',
picture: 'n/a',
body: 'this is the body of the test post'
},
{
_id: new ObjectId("62ef202670ad070b78e928a3"),
title: 'Test Title 2',
picture: 'n/a',
body: 'this is the body of the second test post'
}
]

然而,如果我尝试这个:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blog', {useNewUrlParser: true});
const Schema = mongoose.Schema;
const BlogSchema = new Schema({
title : String,
image: String,
body: String
});
const Model = mongoose.model;
const BlogPost = new Model('posts', BlogSchema);
var AllPosts = BlogPost.find((err, posts) => {
posts;
});
console.log(AllPosts);

我得到这个:

Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: null,
Promise: [Function: Promise],
modelName: 'posts',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: {},
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'posts',
collectionName: 'posts',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://localhost/blog',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise]
},
queue: [],
buffer: true,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { posts },
schema: Schema {
obj: {
title: [Function: String],
image: [Function: String],
body: [Function: String]
},
paths: {
title: [SchemaString],
image: [SchemaString],
body: [SchemaString],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
title: [Function: String],
image: [Function: String],
body: [Function: String],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'find',
options: {},
_conditions: {},
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: null,
Promise: [Function: Promise],
modelName: 'posts',
_closed: false,
opts: [Object],
name: 'posts',
collectionName: 'posts',
conn: [NativeConnection],
queue: [],
buffer: true,
emitter: [EventEmitter]
},
collectionName: 'posts'
},
_traceFunction: undefined,
'$useProjection': true
}

我做错了什么?

谢谢!

您应该使用异步/等待调用。现在,您的AllPosts变量的值为Promise。只需将其更改为:

var AllPosts = await BlogPost.find({});
console.log(AllPosts);
var AllPosts = await BlogPost.find({})
/*OR*/
var AllPosts={};
BlogPost.find({}).then(data=>
{
AllPosts=data;
})
.catch(err=>
{
console.log(err);
})

最新更新