代码之家  ›  专栏  ›  技术社区  ›  William

为Mongoose(Node.js)创建主查询模块

  •  0
  • William  · 技术社区  · 6 年前

    这就是电话:

    let options = { _id: socket.handshake.session.passport.user };
    let q = {};
    let user = await query("User", "findOne", options, q);
    

    以下是它的功能:

    const q = async (c, t, o, q) => {
      c = require(`../models/${c}`);
      let query;
      if (t == "findOne") {
        query = c.findOne(o, q);
      }
      return await query
        .exec()
        .then(results => {
          return results;
        })
        .catch(err => {
          return console.log(err);
        });
    };
    
    module.exports = q;
    

    t 直接而不是在if语句中使用它。

    c = collection (User)
    t = type (the query, findOne is the only one atm)
    o = options (or in this case the selector)
    q = query (what I want changed, if applicable) 
    

    如果需要的话,我并不十分反对把所有的陈述都写出来,但如果可以的话,我想避免。

    0 回复  |  直到 6 年前
        1
  •  0
  •   William    6 年前

    啊哈!我得到了它!函数如下所示:

    const q = async (c, t, o, q) => {
      c = require(`../models/${c}`);
      let query = c[t](o, q);
      return await query
        .exec()
        .then(res => {
          return res;
        })
        .catch(err => {
          return console.log(err);
        });
    };
    
    module.exports = q;