简体   繁体   English

Mongoose Populate返回空数组

[英]Mongoose Populate returns empty array

I am receiving an empty array with the following code: 我收到一个空数组,代码如下:

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'mytestapp');

var SurveySchema = require('../models/Survey.js').SurveySchema;
var Survey = mongoose.model('SurveySchema', SurveySchema, 'surveys');


var UserSchema = require('../models/Survey.js').User;
var User = mongoose.model('user', UserSchema, 'users');

exports.getSurveysForUser = function(User) {
    return function (req, res) {


 User
        .findOne({_id: req.params.userId})
        .populate('surveys')
        .exec(function (err, user){
            if (err) return res.json({error: err})
            else {
                var surveyList=[];
                surveyList = user.surveys;
                console.log(surveyList);
                console.log("user: "+ user);
                res.json(surveyList);

            }
        });
}};

This is the console output: 这是控制台输出:

 [ ]

user: { __v: 2,
  _id: 52939b8c22a7efb720000003,
  email: 'a@b.de',
  password: '202cb962ac59075b964b07152d234b70',
  surveys: []
}

These are the Mongoose models: 这些是Mongoose模型:

exports.SurveySchema = new Mongoose.Schema({
description : String,
questions : [question] });

exports.User = new Mongoose.Schema({
name : String,
email: { type: String, unique: true },
password: { type: String, required: true},
surveys :  [{type: Schema.ObjectId, ref: 'SurveySchema'}] });

Btw: BTW:

I already tried User.findOne(...) and then a Survey.find() in the callback. 我已经尝试过User.findOne(...),然后在回调中尝试了Survey.find()。 It seemed that the second statement was not even executed. 似乎第二个声明甚至没有被执行。 Apparently i am very new to mongoose..and i can't find a way around this problem 显然我对mongoose很新。我无法找到解决这个问题的方法

Do you have any ideas how to help me? 你有什么想法可以帮助我吗? I couldn't really find any helpful solution here, but the problem shouldn't be a big one. 我在这里找不到任何有用的解决方案,但问题不应该是一个大问题。 Thanks in advance, its really keeping me up for days now!! 在此先感谢,它真的让我好几天了!!

Edit: So this is the index.js with the method: 编辑:所以这是index.js与方法:

var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'mytestapp');

var SurveySchema = require('../models/Survey.js').SurveySchema;
var Survey = mongoose.model('SurveySchema', SurveySchema, 'surveys');



var UserSchema = require('../models/Survey.js').User;
var User = mongoose.model('user', UserSchema, 'users');

//.. here are some more methods.. 

exports.getSurveysForUser = function(User) {
return function (req, res) {
 User
            .findOne({_id: req.params.userId})
            .populate('surveys')
            .exec(function (err, user){
                if (err) return res.json({error: err})
                else {
                    var surveyList=[];
                    surveyList = user.surveys;
                    console.log(surveyList);
                    console.log("user: "+ user);
                    res.json(surveyList);

                }
            });
}};

//this is the code, that saves a response to a survey

exports.addResponse = function(ResponseSet) {
    return function (req, res) {
        console.log("bin da: addResponse");
        console.log("response zu: " + req.body.surveyId);
        console.log("von user : " + req.body.userId);

        //für user speichern

        var pUser = User.findOne({_id:req.body.userId}, function (error, user) {

                // Maybe populate doesnt work, because i only push the ID?

               user.surveys.push(Mongoose.Types.ObjectId(req.body.surveyId));

               user.save();

            }
        );



        var pSurvey = Survey.findOne({_id:req.body.surveyId}, function (error, survey) {
                survey.responses.push(Mongoose.Types.ObjectId(req.params.id));
                survey.save();
            }
        );



        //responseSet speichern

        var responseSet = new ResponseSet(req.body);
        responseSet.save(function(error, responseSet) {
            if (error || !responseSet) {
                res.json({ error : error });
            } else {

                res.json(responseSet);
            }
        });
    };

 };

And this is the app.js, which consumes the index.js: 这是app.js,它使用index.js:

var Mongoose = require('mongoose');
var db = Mongoose.createConnection('localhost', 'mytestapp');

var SurveySchema = require('./models/Survey.js').SurveySchema;
var Survey = db.model('surveys', SurveySchema);
var UserSchema = require('./models/Survey.js').User;
var User = db.model('user', UserSchema);

var ResponseSetSchema = require ('./models/Survey.js').responseSet;
var ResponseSet = db.model('responseSet', ResponseSetSchema);

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , passport = require('passport')
  , pass = require('./config/pass')

  , user_routes = require('./routes/user');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views/app');
//app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/views/app'));
app.use(express.cookieParser());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'securedsession' }));
app.use(passport.initialize()); // Add passport initialization
app.use(passport.session()); // Add passport initialization
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.all('/secure', pass.ensureAuthenticated);


app.get('/', function (req, res)
{
    res.render('index.html');
} );

// some more code... 

app.get('/api/secure/userSurveys/:userId', routes.getSurveysForUser(User));

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Hope it helpsto fight the problem! 希望它有助于解决问题! Many many thanks in advance!! 很多人提前感谢!! :) :)

Try changing: 尝试改变:

surveys: [{type: Schema.ObjectId, ref: 'SurveySchema'}] });

to

surveys: [{type: Schema.Types.ObjectId, ref: 'SurveySchema'}] });

Also, make sure you have surveys pushed as children to User.surveys . 此外,请确保您将调查作为子项推送到User.surveys

http://mongoosejs.com/docs/populate.html , here this section talks about your requirement in detail: http://mongoosejs.com/docs/populate.html ,这里将详细介绍您的要求:

Refs to children 适合儿童

We may find however, if we use the aaron object, we are unable to get a list of the stories. 然而,我们可能会发现,如果我们使用aaron对象,我们就无法获得故事列表。 This is because no story objects were ever 'pushed' onto aaron.stories." 这是因为没有任何故事对象被“推”到aaron.stories上。“

Ok, it took quite a lot to figure out the issue: 好吧,找出问题花了很多时间:

exports.getSurveysForUser = function(User) {
...
};

The var User - model is not being injected into the scope properly. var用户模型未正确注入范围。 Change to: 改成:

exports.getSurveysForUser = (function(User) {
...
})(User);

The returned function's signature for middleware do not require User model to be passed as they are re-initiated and passed within the middleware code. 返回的函数的中间件签名不需要传递User模型,因为它们在中间件代码中被重新启动和传递。

In index.js, change this 在index.js中,更改此内容

app.get('/api/secure/userSurveys/:userId', routes.getSurveysForUser(User));

to

app.get('/api/secure/userSurveys/:userId', routes.getSurveysForUser());

I also request you to self test your code and read as many docs as possible. 我还要求您自行测试您的代码并阅读尽可能多的文档。 Also, there can be multiple ways of reaching your goals. 此外,可以通过多种方式实现目标。 With time and practice you will conquer them all. 随着时间和实践,你将征服他们所有。 Good luck! 祝好运!

So i found a solution! 所以我找到了解决方案! Firstly it seemed, that the mongoose Schemas were not correctly required. 首先,似乎没有正确要求猫鼬Schemas。

So in the models, i did mongoose.model('modelname', schemaname); 所以在模型中,我做了mongoose.model('modelname',schemaname); for every model and now i only use mongoose.model(...) for every model in the index.js. 对于每个模型,现在我只对index.js中的每个模型使用mongoose.model(...)。

Secondly i found out about an even more critical thing: There were suddenly no user.surveys for my testuser anymore! 其次,我发现了一个更重要的事情:我的testuser突然没有user.surveys了! I am sure that it was filled with surveys a few days ago. 我相信几天前它已经充满了调查。 Because i tested my code several times and some surveys were pushed to that collection. 因为我多次测试我的代码,并且一些调查被推送到该集合。 Maybe i dropped the collection it in some testing..i don't really remember. 也许我把它收集在一些测试中......我真的不记得了。 So i pushed a survey manually in the mongodb console and tested it again --> worked! 所以我在mongodb控制台中手动调查并再次测试 - >工作! the user.surveys were populated! user.surveys已填充! maybe the function worked yesterday and didn't need any change. 也许这个功能在昨天工作,不需要任何改变。 I am so sorry, if that was a waste of time. 对不起,如果这是浪费时间的话。

Bad thing is, that right now the exports.addResponse(....) is only saving a response, but is not pushing the IDs to the arrays user.surveys and survey.responses. 不好的是,现在exports.addResponse(....)只保存响应,但没有将ID推送到数组user.surveys和survey.responses。 This seems to be a synchronizing Problem and i will figure that out somehow. 这似乎是一个同步问题,我会以某种方式解决这个问题。

Anyways, thank you for your help and time! 无论如何,谢谢你的帮助和时间!

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

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