Javascript 如何将Mongodb集合结果转换为数组?
我想将我的MongoDB收集结果作为数组发送到服务-(准确地说是Algolia) MongoDB返回的结果不是数组格式。因此,我在想是否有办法将收集结果转换为数组Javascript 如何将Mongodb集合结果转换为数组?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我想将我的MongoDB收集结果作为数组发送到服务-(准确地说是Algolia) MongoDB返回的结果不是数组格式。因此,我在想是否有办法将收集结果转换为数组 meme.find({}, (err, meme) => { const memes = meme.map(m => m); // Use the array, pass it to a service, or pass to a callback }); 这就是它的回报: { _id: 5b30c318ca1e
meme.find({}, (err, meme) => {
const memes = meme.map(m => m);
// Use the array, pass it to a service, or pass to a callback
});
这就是它的回报:
{ _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);
});
});
我如何操作该进程,以便它可以被数组调用
谢谢 只需使用map。它将遍历每个meme并将它们添加到数组中
meme.find({}, (err, meme) => {
const memes = meme.map(m => m);
// Use the array, pass it to a service, or pass to a callback
});
您使用的是Mongoose,因此
meme.find
回调中的meme
是一个数组;您正在对其进行迭代,并分别对每个元素进行控制台日志记录。也许我不明白你的问题,没错。如何将其转换为数组?meme
已经是一个数组。当我运行代码时,它仍然返回对象meme.find({},(err,meme)=>{const memes=meme.map(m=>m);console.log(typeof memes);//使用数组,将其传递给服务,或传递给回调})
注释部分//使用数组、将其传递给服务或传递给回调
如何传递给回调@杰克·米勒