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

时间:2018-06-26 23:29:23

标签: javascript node.js mongodb mongoose

我想将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); 
  });
});

我如何操纵该过程使其可以为数组?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

The cursor object returned by find() has a toArray() method.

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