迭代Mongoose上的Docs

时间:2018-04-16 07:48:41

标签: javascript node.js mongoose

我在mongodb中插入带有insertMany函数的mongoose元素数组。一切都很好,但我需要把每个元素都拿走他的身份。当我插入这些元素时,我会收到一系列文档但我无法迭代它们。

你有任何解决方案吗?

代码示例:

const docsExamples = await Examples.insertMany(req.body.examples);

1 个答案:

答案 0 :(得分:1)

您可以对insertMany返回的docs数组使用.map()来返回一个只有id的新数组,如下所示:

#!/usr/bin/env node
'use strict';

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Schema = mongoose.Schema;

const schema = new Schema({
  name: String
});

const Test = mongoose.model('test', schema);

const tests = [];

for (let i = 0; i < 10; i++) {
  tests.push(new Test({ name: `test${i}`}));
}

async function run() {
  await mongoose.connection.dropDatabase();
  const docs = await Test.insertMany(tests);
  const ids = docs.map(d => d.id);
  console.log(ids);
  return mongoose.connection.close();
}

run();

输出:

stack: ./49852063.js
[ '5ad47da0f38fec9807754fd3',
  '5ad47da0f38fec9807754fd4',
  '5ad47da0f38fec9807754fd5',
  '5ad47da0f38fec9807754fd6',
  '5ad47da0f38fec9807754fd7',
  '5ad47da0f38fec9807754fd8',
  '5ad47da0f38fec9807754fd9',
  '5ad47da0f38fec9807754fda',
  '5ad47da0f38fec9807754fdb',
  '5ad47da0f38fec9807754fdc' ]
stack: