【问题标题】:mongoose find all not sending callback猫鼬发现所有不发送回调
【发布时间】:2018-09-24 06:29:06
【问题描述】:

new mongoose,我发现 Modal.find() 有点麻烦。

我有一个 expressjs api 端点 /latest/all 应该返回我的 mongodb 中的所有产品。

// Get latest listings
  router.get('/latest/all', function (req, res, next) {
  var json = Product.getAllProductListings();

  res.send(json);
});

以下是 product.js 模式。

   'use strict';

var mongoose = require('mongoose');


// Product Schema
var ProductSchema = mongoose.Schema({
    category: {
        type: String,
        index: true
    },
    name: {
        type: String
    },
    state: {
        type: String
    },
    target: {
        type: String
    }
});

var Product = module.exports = mongoose.model('Product', ProductSchema);

//Add new product request
module.exports.createProductReq = function (newProdReq, callback) {

    newProdReq.save(callback);

};


//Find all products


//Find One
module.exports.getProductByCategory = function (category, callback) {
    var query = {category: category};
    Product.findOne(query, callback);
};

//Find All
module.exports.getAllProductListings = function (docs) {
    var query = {};
    Product.find(query, function (err, docs) {
        console.log(docs);
    });


};

console.log(docs);在我的控制台窗口中也显示我期望的内容,但是“docs”没有以与之前的“findOne”相同的方式传递给 getAllProductListings。

getAllProductListings 的函数中只有一个返回值,因为它不带参数。

我肯定在做一些愚蠢的事情,所以如果可以的话,请赐教。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    因为getAllProductListings是异步的,所以需要在回调中发送响应:

    // Get latest listings
    router.get('/latest/all', function (req, res, next) {
    Product.getAllProductListings(res);
    });
    

    在您的product.js 中:

    //Find All
    module.exports.getAllProductListings = function (response) {
    var query = {};
    Product.find(query, function (err, docs) {
        console.log(docs);
        response.send(docs);
    });
    

    【讨论】:

    • 如果您不介意,我有一个后续问题。当我只需要返回 JSON 数据时,这对于相关任务非常有效。如何将其与页面一起发送。例如,下面的代码显示了我在想什么。 // Get latest listings page router.get('/latest', function (req, res, next) { Request.getAllRequestListings(res); res.render('latest'); }); // Get latest listings from API router.get('/latest/all', function (req, res, next) { Request.getAllRequestListings(res); });
    猜你喜欢
    • 2015-10-08
    • 2013-08-05
    • 2013-11-01
    • 2017-06-06
    • 2019-04-12
    • 2015-11-06
    • 1970-01-01
    • 2021-10-10
    • 2019-05-19
    相关资源
    最近更新 更多