如何将像(find,findOneAndUpdate)这样的猫鼬查询放在函数中与我的路由不同的文件中?

时间:2019-05-19 20:20:30

标签: node.js express mongoose

如何将像(find,findOneAndUpdate)这样的猫鼬查询放在函数中与我的路由不同的文件中?我想在项目的多个地方重用这些查询。 这是我的简单项目: 项目/     助手/        helper.js     楷模/        customer.model.js      app.js

我的初始app.js文件如下所示。

let express = require("express");
let app = express();
let mongoose = require("mongoose");

let Customer = require("./models/customer.model");
let helper = require("./helpers/helper");

mongoose.connect("mongodb://localhost/rest-api-workshop", {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false
});

app.use("/test",(req, res)=> {
    Customer.find({}, "-_id")
    .then(doc => {
        return res.json(doc);
    })
    .catch(err => {
        return res.status(500).json(err);
    })
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.info(`Server has started on ${PORT}`));

我的customer.model.js文件如下所示:     let mongoose = require(“ mongoose”);

let CustomerSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    email: {
        type: String
    }

}, { collection: 'myCustomers' });

module.exports = mongoose.model("Customer", CustomerSchema);

运行http://localhost:3000/test时,仅使用这两个文件都可以很好地从myCustomers集合中获取结果。

当我尝试将查找查询放在另一个文件中的函数中时,运行http://localhost:3000/test时不返回任何内容。在这种方法下,这是我的新app.js文件:

let express = require("express");
let app = express();
let mongoose = require("mongoose");

let Customer = require("./models/customer.model");
let helper = require("./helpers/helper");

mongoose.connect("mongodb://localhost/rest-api-workshop", {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false
});

app.use("/test",(req, res)=> {
    var x = helper.runQuery();
    return res.json(x);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.info(`Server has started on ${PORT}`));

我的helper.js文件如下。

module.exports = {
    runQuery: function () {
        let Customer = require("../models/customer.model");
        Customer.find({}, "-_id")
            .then(doc => {
                return doc;
            })
            .catch(err => {
                return "invalid";
            })
    }
}

为什么第二种方法不起作用?我相信这与节点js的异步特性有关,但不知道如何解决。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在您的 helper.js 中执行类似的操作

    import {
      OPTIONS_SELECT,
    } from '../actions/actionTypes';

    const initialState = {
      selectedOptions:[],
    };

    const reducer = (state = initialState, action) => {
      switch (action.type) {
        case OPTIONS_SELECT:
          return {
            ...state,
            selectedOptions: [...state.selectedOptions, action.selectedOptions],
          };
        default:
          return state;
      }
    };
    export default reducer;

然后在 app.js

 const Model = require('path to model');
    exports.runQuery = (req, res) => {
      Model.find()
        .then(data => {
          // do something here 
        })
        .catch(err => {
          // handle here
        });
    };