如何获得在数组中已存在的嵌入式文档中找到的一系列嵌入式文档?

时间:2019-05-14 09:55:41

标签: javascript node.js mongodb mongoose

如何在一系列嵌入式文档中的文档中获取一系列嵌入式文档?

我一直在尝试使用聚合,匹配,展开和匹配方法,而我只是得到一个空数组。

const emailComboSchema = new mongoose.Schema({
  combo: {
    type: Number,
    enum: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    minlength: 1,
    maxlength: 2
  },
  email: {
    type: String,
    minlength: 5,
    maxlength: 53,
    lowercase: true,
    trim: true,
    match: [
      /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
      "Please fill a valid email address"
    ]
  },
  hasResponse: Boolean
});

const nameSchema = new mongoose.Schema({
  fn: {
    type: String,
    minlength: 2,
    maxlength: 50,
    trim: true
  },
  ln: {
    type: String,
    minlength: 2,
    maxlength: 50,
    trim: true
  },
  emails: [emailComboSchema],
  notes: {
    type: String,
    maxlength: 512,
    trim: true
  }
});


const Data = new mongoose.model(
  "Data",
  new mongoose.Schema({
    domain: {
      type: String,
      required: true,
      minlength: 4,
      maxlength: 50,
      trim: true
    },
    names: [nameSchema],
    domainIsValid: {
      type: Boolean,
      required: false
    }
  })
);

// Get all Names Route by dataId
router.get("/:dataId/:nameId", auth, async (req, res) => {
  let emails = await Data.aggregate(
    [
      {
        $match: {
          _id: mongoose.Types.ObjectId(req.params.dataId)
        }
      },
      { $unwind: "$names" },
      {
        $match: {
          "names._id": mongoose.Types.ObjectId(req.params.nameId)
        }
      },
      { $unwind: "$emails" },
      { $project: { _id: 0, "names.emails": "$emails" } }
    ],
    function(err, result) {
      if (err) {
        next(err);
      } else {
        res.json(result);
      }
    }
  );
  res.send(emails);
});

当我发送get请求时,我得到一个空数组,但是我希望有一个emailCombo嵌入式文档数组。

0 个答案:

没有答案