gpt4 book ai didi

node.js - Node JS - 当我想显示来自 Mongoose 的列表时异步

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:15 25 4
gpt4 key购买 nike

当我想在 ejs 中将 Mongoose (MongoDB) 的数据列表显示到我的前端时遇到问题

例如:

var User = require("./models/user");
var Houses = require("./models/house");

app.get("/", function(req, res){
var list_houses = [];
for(var i=0; i<req.user.city.length; i++)
{
Houses.find({'city': req.user.city[i]}, function(err, result){
if(err)console.log(err);
if(result){
list_houses = list_houses.concat(result);//add array result to array list_prices
}
});
}
res.render("/prices_houses",{list_houses: list_houses});
});

我找到了“async”模块,但两者都不起作用,我的代码是:

var User = require("./models/user");
var Houses = require("./models/house");
var async = require('async');

app.get("/", function(req,res){
var list_houses = [];
async.waterfall([
async.each(req.user.city, function(result, callback){
Houses.find({'city': result}, function(err, result){
if(err)console.log(err);
if(result){
list_houses = list_houses.concat(result);
}
});
});
], function(arg1, callback){
res.render("/prices_houses", {list_houses: list_houses});
});
});

当我想在ejs中显示'list_houses.length'时,它显示:0

<%=list_houses.length%>

我在 Mongoose 中的架构是:

var User = new mongoose.Schema({
city : [String]
...
});

var House = new mongoose.Schema({
city: String
price: Double
});

我知道问题出在异步,但我不知道如何解决。请帮我解决这个问题。

最佳答案

我认为你把事情搞得太复杂了。似乎您可以仅使用 $in 运算符来实现此目的。大致如下:

Houses.find({'city': {$in: req.user.city}}, function(err, results){
if(err)console.log(err);
console.log(results); // this should be an array of all houses in all cities that the user has in their city array
});

关于node.js - Node JS - 当我想显示来自 Mongoose 的列表时异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41628130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com