问题描述
新猫鼬,我发现Modal.find()有点麻烦.
new mongoose and I am finding the Modal.find() a little troublesome.
我有一个expressjs api端点/latest/all,应该返回mongodb中的所有产品.
I have a expressjs api endpoint /latest/all that should return all products in my mongodb.
// Get latest listings
router.get('/latest/all', function (req, res, next) {
var json = Product.getAllProductListings();
res.send(json);
});
以下是product.js模式.
The below is a product.js modal.
'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.
The console.log(docs); displays what I expect it too in my console window, however the "docs" is not being passed to the getAllProductListings in the same fashion as the "findOne" before hand.
我在getAllProductListings函数中只有一个返回值,因为它没有参数.
I have only one return value in the function for getAllProductListings since it doesn't take parameters.
我绝对是在做些愚蠢的事情,所以请尽我所能.
Am definitely doing something silly so please enlighten me if you can.
推荐答案
由于getAllProductListings
是异步的,因此您需要在回调中发送响应:
Because getAllProductListings
is asynchronous, you need to send the response in the callback :
// 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);
});
这篇关于猫鼬找到所有不发送回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!