【问题标题】:How to update document by ID without using model如何在不使用模型的情况下按 ID 更新文档
【发布时间】:2017-10-05 21:14:05
【问题描述】:

我有 Card 模型,并且我有一个 API,我正在通过 ID 查找文档。

app.post("/api/postcomment", async (req,res) => {
  const data = req.body
  const reqUrl = req.headers.referer
  const re = new RegExp('([a-zA-Z0-9]*$)', 'i')
  const fixedUrl = reqUrl.match(re)

  try {
    await Card.update({_id: fixedUrl}, {$push:{'comments': data}})
    const card = await Card.findById(fixedUrl)
    return res.json(card)
  } catch (err) {
    throw err
  }
})

它工作正常。但现在我有几个模型。所有人都应该以同样的方式为他们工作。但是我怎样才能使这个代码对每个模型都可重用呢? 或者也许有一种方法可以将我的模型名称传递给 API?然后像这样使用它:

app.post("/api/postcomment", async (req,res, modelName) => {
  const data = req.body
  const reqUrl = req.headers.referer
  const re = new RegExp('([a-zA-Z0-9]*$)', 'i')
  const fixedUrl = reqUrl.match(re)

  try {
    await modelName.update({_id: fixedUrl}, {$push:{'comments': data}})
    const item = await modelName.findById(fixedUrl)
    return res.json(item )
  } catch (err) {
    throw err
  }
})

【问题讨论】:

    标签: node.js database mongodb express mongoose


    【解决方案1】:

    解决方案1:您可以创建两个辅助函数并从路由器调用。两个函数都接受模型对象:

    let updateDocument = (model, fixedUrl, data) => {
      return model.update({ _id: fixedUrl }, { $push: { comments: data }})
    }
    
    let getDocument = (model, fixedUrl) => {
      return model.findById(fixedUrl)
    }
    
    app.post("/api/postcomment", async (req, res, modelName) => {
      const data = req.body
      const reqUrl = req.headers.referer
      const re = new RegExp('([a-zA-Z0-9]*$)', 'i')
      const fixedUrl = reqUrl.match(re)
    
      try {
        await updateDocument(Card, fixedUrl, data)
        const item = await getDocument(Card, fixedUrl)
        return res.json(item )
      } catch (err) {
        throw err
      }
    })
    

    解决方案2:更好的解决方案是创建一个具有通用功能的基类(服务)。并为每个模型扩展它:

    class BaseService {
      constructor(model) {
        this.model = model;
      }
    
      getDocument(data) {
        return this.model.findOne(...);
      }
    
      updateDocument(data) {
        return this.model.update(...);
      }
    }
    
    class CardService extends BaseService {
      constuctor() {
        super(Card);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2011-04-21
      • 2020-10-18
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 2016-04-11
      相关资源
      最近更新 更多