如何避免猫鼬嵌套在数组中的对象中键的重复值

时间:2019-06-26 16:53:31

标签: arrays node.js mongodb object mongoose

这是我的代码的样子,我已经尝试过addToset,elemMatch和其他我在stackoverlow上看到的东西,但似乎没有任何作用

router.put(
  "/stock",
  auth,
  [
    check("ticker", "symbol is require or incorrect.")
      .not()
      .isEmpty(),
    check("name", "Stock name is required")
      .not()
      .isEmpty(),
    check(
      "qty",
      "Quantity of the stock purchased is required and should be numeric"
    )
      .isNumeric()
      .not()
      .isEmpty(),
    check(
      "dateInvested",
      "Date of investment is required and should be valid date format."
    )
      .not()
      .isEmpty(),
    check(
      "priceInvested",
      "Price of the stock purchased is required and should be numeric"
    )
      .isNumeric()
      .not()
      .isEmpty()
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { ticker, name, qty, dateInvested, priceInvested } = req.body;

    //Build Portfolio object
    const newStock = {
        ticker,
        name,
        qty,
        dateInvested,
        priceInvested
    };

    try {
      let portfolio = await Portfolio.updateOne({ user: req.user.id });

      //add stock to the portfolio
      portfolio.stocks.unshift(newStock);

      await portfolio.save();

      res.json(portfolio);

    } catch (err) {
      console.error(err.message);
      res.status(500).send("Sever Error");
    }
  }
);

这是输出,在这里我不想重复股票代码。

{
    "_id": "5d0757fc0747c72cd0e4da04",
    "user": "5d01abfc0f97b52dac7044bf",
    "portname": "MyPortfolio",
    "goal": "Make a profit of 50%",
    "stocks": [
        {
            "_id": "5d0758050747c72cd0e4da06",
            "ticker": "AAPL",
            "name": "Apple",
            "qty": 22,
            "dateInvested": "2018-06-30T07:00:00.000Z",
            "priceInvested": 99
        },
        {
            "_id": "5d0758000747c72cd0e4da05",
            "ticker": "AAPL",
            "name": "Apple",
            "qty": 22,
            "dateInvested": "2018-06-30T07:00:00.000Z",
            "priceInvested": 99
        }
    ],
    "date": "2019-06-17T09:06:04.412Z",
    "__v": 2
}

如果您认为我应该更改架构并尝试其他有用的方法,那么我还应该在猫鼬架构中尝试将unique分配为true吗?

0 个答案:

没有答案