简体   繁体   English

猫鼬数据库从两个文档返回数据

[英]mongoose db returning data from two documents

I am creating my first mongoose database app. 我正在创建我的第一个猫鼬数据库应用程序。 I am trying to write an express API call that returns an object that contains data from two documents. 我正在尝试编写一个快速API调用,该调用返回一个包含两个文档中数据的对象。 Whenever I call the /data route I get an empty array back. 每当我调用/ data路由时,我都会得到一个空数组。 I added two console.log lines and the output is: 我添加了两条console.log行,输出为:

test2
test1

What can I do to have the forEach finish before returning the result? 返回结果前,我该怎么做才能使forEach完成?

Here's the code: 这是代码:

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);
        }
    });
});

This is the result I would like to get 这是我想要得到的结果

[ { 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 } ] } ]

The primary issue is that you are sending back the results in the response before they have been fully retrieved. 主要问题是您要在完全检索结果之前将结果发送回响应中。 Your res.json(results) is outside the Message.find(...) callback. 您的res.json(results)Message.find(...)回调之外。 Additionally, since you push the attendee object onto the results array in that same callback, it too will be missing, and your returned results array will simply be the original empty array. 此外,由于您在同一回调中将与会者对象推送到结果数组上,因此也将丢失该对象,并且返回的结果数组将只是原始的空数组。

You need something more like this: 您需要这样的东西:

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);
            })
        }
    });
});

I solved my own problem by using a mongoose feature called populate. 我通过使用名为populate的猫鼬功能解决了自己的问题。 http://mongoosejs.com/docs/populate.html . http://mongoosejs.com/docs/populate.html I was able to simplify my code a lot: 我能够简化很多代码:

    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);
        });
    }); 

The real magic of this code is in the schemes: 该代码的真正魔力在于方案:

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);

and

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM