我正在创建我的第一个mongoose数据库应用程序。我正在尝试编写一个快速API调用,它返回一个包含两个文档数据的对象。每当我调用/ data路由时,我都会得到一个空数组。我添加了两个console.log行,输出是:
test2
test1
在返回结果之前,我该怎么做才能完成forEach?
以下是代码:
router.route('/data')
//get all data
.get(function(req, res) {
var results = [];
Attendee.find(function(err, attendees) {
if (err) {res.send(err);}
else {
attendees.forEach(function(attendee) {
Message.find({userID: attendee._id}, function(err,messages){
results.push({
attendee: attendee,
messages: messages
});
});
console.log("test1");
console.log(results);
});
console.log("test2");
res.json(results);
}
});
});
这是我想要的结果
[ { attendee:
{ _id: 53c060e7fb90e3d709d6bdae,
fullName: ‘joe smith,
phoneNumber: '+555’,
__v: 0 },
messages:
[ { _id: 53c06887fb1d24fb095fd365,
phoneNumber: '+555',
body: ‘test’,
userID: '53c060e7fb90e3d709d6bdae',
sid: 'SMa86f2914986d4b04067d7f054da205a5',
__v: 0 },
{ _id: 53c41cf3d068393d17dc0dbf,
phoneNumber: '+555',
body: ‘test’,
userID: '53c060e7fb90e3d709d6bdae',
sid: 'SM4f6c64ca7b39e6caee9859e761a2850d',
__v: 0 },
{ _id: 53c421e16371e54f171751cf,
phoneNumber: '+555',
body: ‘test’,
userID: '53c060e7fb90e3d709d6bdae',
sid: 'SM1097eae33e4f53cdcdad32651c016437',
__v: 0 },
{ _id: 53c421e16371e54f171751d0,
phoneNumber: '+555',
body: ‘test’,
userID: '53c060e7fb90e3d709d6bdae',
sid: 'SM5a452e51c995d7ad6ad8f7b85cec80b0',
__v: 0 } ] } ]
答案 0 :(得分:0)
主要问题是您在完全检索之前将结果发送回响应中。您的res.json(results)
不在Message.find(...)
回调范围内。此外,由于您将与会者对象推送到同一回调中的结果数组中,因此它也将丢失,并且返回的结果数组将只是原始的空数组。
你需要更像这样的东西:
router.route('/data')
//get all data
.get(function(req, res) {
var results = [];
Attendee.find(function(err, attendees) {
if (err) {res.send(err);}
else {
q.all(attendees.map(function(attendee) {
return Message
.find({userID: attendee._id}, "")
.exec()
.then(function(messages) {
results.push({
attendee: attendee,
messages: messages
});
})
}))
.then(function() {
res.json(results);
})
}
});
});
答案 1 :(得分:0)
我通过使用名为populate的mongoose功能解决了我自己的问题。 http://mongoosejs.com/docs/populate.html。我能够简化我的代码:
router.route('/data')
//get all data
.get(function(req, res) {
Attendee.find().populate('messages').exec(function(err, attendees){
if (err) {res.send(err);}
res.json(attendees);
});
});
此代码的真正神奇之处在于以下方案:
var mongoose = require('mongoose');
var AttendeeSchema = new mongoose.Schema({
fullName: {
type: String,
require: true
},
dateJoined: {
type: Date,
require: true
},
phoneNumber: {
type: String,
required: true
},
messages: [{
type: mongoose.Schema.Types.ObjectId, ref: "Message"
}]
});
module.exports = mongoose.model('Attendee', AttendeeSchema);
和
var mongoose = require('mongoose');
var MessageSchema = new mongoose.Schema({
_userID: {
type: String,
ref: 'Attendee'
},
phoneNumber: {
type: String,
require: true
},
date: {
type: Date,
require: true
},
body: {
type: String,
required: true
},
sid: {
type: String,
required: true
}
});
module.exports = mongoose.model('Message', MessageSchema);