亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在貓鼬中正確創建數組架構并按給定條件進行過濾?

如何在貓鼬中正確創建數組架構并按給定條件進行過濾?

慕萊塢森 2022-09-02 16:19:49
我對mongodb和mongoose很陌生,所以我請你幫助我。我有一個API,它可以工作,現在我想通過過濾給定的參數來擴展它。我有一個訂單模型,它指向兩個不同的文檔集合材料和用戶模式,并具有數量元素。let Order = new Schema({    materials:     {        type: Array,        material: {             type: mongoose.Schema.Types.ObjectId,            ref: 'Material'        },        qty: {            type: Number        }    },    userId: {        type: Schema.Types.ObjectId,        ref: 'User'    }}, {    collection: 'orders'})另外,我有創建訂單的方法:  exports.createOrder = (req, res) => {    if (!req.body.user) {        res.status(400).send({message: 'Content can not be empty!'});    }    const order = new Order({        materials: req.body.materials,        userId: req.body.user    });    order    .save(order)    .then(data => {        res.send(data);    })    .catch(err => {        res.status(500).send({          message:            err.message || "Some error occurred while creating the Order."        });      });   }如果我只創建訂單填充物料 ID,它會在過濾器請求中按給定的物料 ID 創建和過濾。發布請求過濾器請求但是,如果我試圖指出數量,它不會出現在響應中。以數量發布請求以上一個文檔 ID 結尾的篩選器請求有我的問題是:如何以我需要的方式創建訂單(物料ID和數量必須保留)以及如何對它們執行過濾操作?
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

我的錯誤在于我如何創建訂單以及我提出過濾請求的方法。


創建以數組類型存儲數據的訂單的正確方法如下


exports.createOrder = (req, res) => {

    if (!req.body.user) {

        res.status(400).send({message: 'Content can not be empty!'});

    }

    const order = new Order({

        materials: {material: req.body.materials, qty: req.body.qty},

        userId: req.body.user

    });

    order

    .save(order)

    .then(data => {

        res.send(data);

    })

    .catch(err => {

        res.status(500).send({

          message:

            err.message || "Some error occurred while creating the Order."

        });

      });

}

如您所見,差異是我形成材料陣列的方式。


接下來的事情是在過濾器請求中


exports.filterOrder = (req, res) => {

  Order.find({"materials.material": req.body.material})

  .then(data => {

    console.log(data);

    res.send(data);

  })

  .catch(err => {

    res.status(500).send({

      message:

        err.message || "Some error occurred while retrieving Orders."

    });

  });

}

如果我需要過濾包含必要材料的訂單,我需要將數組的子元素放在帶有點表示法的引號中。如果需要,這也將與“material.qty”參數一起使用。


查看完整回答
反對 回復 2022-09-02
  • 1 回答
  • 0 關注
  • 65 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號