Vue mongoose 連接口

△ 增:

post()
insertMany()

  • 接口
router.post('/url', function(req,res) {
    var xxx = req.body.xxx;
    ……
    XX.insertMany({
      xxx: xxx
      ……
    }, function(err,docs) {
      if(err) {
        console.log(err)
      } else {
        res.json({
          status: '200',
          msg:"插入成功",
          result:docs,
        })            
      }
    })
});

傳參:req.body.xxx

  • 前端
this.$axios
    .post("/api/.../url", {
        xxx: this.xxx,
    })
    .then(res => {
        if (res.data.status == "200") {}
    });

△ 刪:

delete()
deleteOne()

  • 接口
router.delete("/url", (req, res) => {
  var id = req.body.id;
  XX.deleteOne({_id: id}, function(err,data) {})
});

傳參:req.body.xxx

  • 前端
this.$axios
    .delete("/api/.../url", { 
      data: {
        id: this.desserts[this.i]._id
    }})
    .then(res => {
      if (res.data.status == "200") {}
    }); 

傳給後臺的數據需要用 data:{}包裹。

△ 改:

put()
findOneAndUpdate()

  • 接口
router.put("/url", (req, res) => {
  var index = req.body.index;
  var xxx = req.body.xxx;
  XX.findOneAndUpdate(
    { _id: index },
    { "$set": { "xxx": xxx } },
    { "new": true }
    ,function(err,data) {})
});

傳參:req.query.xxx

  • 前端
this.$axios
    .put("/api/.../url", {
        index: this.-._id,
        xxx: this.xxx
    })
    .then(res => {
        if (res.data.status == "200") {}
});

△ 查:

get()
find()
findOne()

  • 接口
router.get('/url',function(req,res) {
  ……
  XX.find(xxx, function(err,data){});
});

傳參:req.query.xxx

  • 前端
this.$axios
    .get("/api/.../url", {
      params: {
        item: this.selected
      }
    })
    .then(res => {
      if (res.data.status == "200") {}
    });

△ 多表聚合查詢:

aggregate()
$lookup
$unwind
$match

  • 接口
router.get('/url',(req,res) => {
  var xxx = req.query.xxx;
  XX.aggregate([{
    $lookup: {  //聚合表
      from:"YY",  //關聯數據表名
      localField:"yy_id",   //當前字段
      foreignField:"_id",  //關聯表字段
      as:"item"
    }
  },{
    $unwind: { // 拆分子數組
      path: "$item",
      preserveNullAndEmptyArrays: true // 空的數組也拆分
    },
  },{
    $match: {  //查找條件
      "xx_id": ObjectId(id)
    }
  }] ,function(err,data) {})
})

如果三表聚合查詢:就多加一個lookuplookup聚合和unwind拆分。

⚠️ $lookup和$unwind需要用{}包裹。

  • 前端
this.$axios
    .get("/api/.../url", {
      params: {
        xxx: this.xxx
      }
    })
    .then(res => {});


  • 從數組中匹配對應字段:

    "xx": { $in: [xx]} 放[數組]裏。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章