如何将Mongodb集合结果转换为数组?



我想将我的MongoDB集合结果作为数组发送到服务-(准确地说是Algolia(。

MongoDB返回的结果不是数组格式。所以我在考虑是否有办法将收集结果转换为数组。

这是它返回的内容:

{ _id: 5b30c318ca1ea60cb8a55d2f,
memeid: 'Z3Q7NC',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529922328/test/adam-levine_nxqpnt.gif',
tags: 'laugh,laughing,laughing uncontrollaby ',
caption: '',
imgs: 'adam-levine.gif',
__v: 0,
uploadDate: 2018-06-25T10:25:28.940Z,
tagarray: [ 'laugh', 'laughing', 'laughinguncontrollaby' ],
views: 500 }
{ _id: 5b30c759ca1ea60cb8a55d30,
memeid: '2oIjDP',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529923417/test/Debffc4XkAAuvLj_mvzvpz.jpg'
tags: 'zuma',
caption: '',
imgs: 'Debffc4XkAAuvLj.jpg',
__v: 0,
uploadDate: 2018-06-25T10:43:37.859Z,
tagarray: [ 'zuma' ],
views: 2000 }
{ _id: 5b30d4b22904771be030db62,
memeid: 'eLT1F',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529926834/test/crying_b6fjaf.gif',
tags: 'laugh',
caption: '',
imgs: 'crying.gif',
__v: 0,
uploadDate: 2018-06-25T11:40:34.649Z,
tagarray: [ 'laugh' ],
views: 0 }

我期待什么:

[
{ _id: 5b30c318ca1ea60cb8a55d2f,
memeid: 'Z3Q7NC',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529922328/test/adam-levine_nxqpnt.gif',
tags: 'laugh,laughing,laughing uncontrollaby ',
caption: '',
imgs: 'adam-levine.gif',
__v: 0,
uploadDate: 2018-06-25T10:25:28.940Z,
tagarray: [ 'laugh', 'laughing', 'laughinguncontrollaby' ],
views: 500 }
{ _id: 5b30c759ca1ea60cb8a55d30,
memeid: '2oIjDP',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529923417/test/Debffc4XkAAuvLj_mvzvpz.jpg'
tags: 'zuma',
caption: '',
imgs: 'Debffc4XkAAuvLj.jpg',
__v: 0,
uploadDate: 2018-06-25T10:43:37.859Z,
tagarray: [ 'zuma' ],
views: 2000 }
{ _id: 5b30d4b22904771be030db62,
memeid: 'eLT1F',
url: 'http://res.cloudinary.com/memeafrica/image/upload/v1529926834/test/crying_b6fjaf.gif',
tags: 'laugh',
caption: '',
imgs: 'crying.gif',
__v: 0,
uploadDate: 2018-06-25T11:40:34.649Z,
tagarray: [ 'laugh' ],
views: 0 }
]

我的代码:

meme.find({}, (err, meme) => {
meme.forEach((meme) => {
console.log(meme); 
});
});

如何操作进程使其可以是数组?

谢谢!

find()返回的游标对象具有toArray()方法。

meme.find().toArray((err, memes) => {
console.log("retrieved memes:");
console.log(memes);
});

只需使用地图。它将遍历每个模因并将它们添加到数组中。

meme.find({}, (err, meme) => {
const memes = meme.map(m => m);
// Use the array, pass it to a service, or pass to a callback
});

最新更新