猫鼬填充返回空数组 [英] Mongoose Populate returns empty array

查看:102
本文介绍了猫鼬填充返回空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到的空数组包含以下代码:

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

            }
        });
}};

这是控制台输出:

 [ ]

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

这些是猫鼬模型:

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

顺便说一句:

我已经尝试了User.findOne(...),然后在回调中尝试了Survey.find().似乎第二条语句甚至没有执行.显然,我对猫鼬非常陌生..我找不到解决此问题的方法

I already tried User.findOne(...) and then a Survey.find() in the callback. 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

您有什么想法可以帮助我吗? 我在这里真的找不到任何有用的解决方案,但问题不应该是一个大问题. 在此先感谢您,这真的让我好几天了!

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!!

这是带有方法的index.js:

So this is the index.js with the method:

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

 };

这是app.js,它消耗了index.js:

And this is the app.js, which consumes the 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!! :)

推荐答案

所以我找到了解决方案! 首先,似乎猫鼬模式不是正确需要的.

So i found a solution! Firstly it seemed, that the mongoose Schemas were not correctly required.

所以在模型中,我做了mongoose.model('modelname',schemaname);对于每个模型,现在我只对index.js中的每个模型使用mongoose.model(...).

So in the models, i did mongoose.model('modelname', schemaname); for every model and now i only use mongoose.model(...) for every model in the index.js.

第二,我发现了一个更关键的事情:突然没有user.surtests为我的测试用户了!我确信几天前它充满了调查.因为我多次测试了我的代码,所以一些调查被推到了那个集合中.也许我在一些测试中丢掉了它..我真的不记得了.因此,我在mongodb控制台中手动推送了一项调查,然后再次对其进行了测试->起作用了! user.surveys已填充!也许该功能昨天就起作用了,不需要任何更改.很抱歉,如果那是浪费时间.

Secondly i found out about an even more critical thing: There were suddenly no user.surveys for my testuser anymore! 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! the user.surveys were populated! maybe the function worked yesterday and didn't need any change. I am so sorry, if that was a waste of time.

不好的是,现在exports.addResponse(....)仅保存响应,但没有将ID推送到user.surveys和survey.responses数组.这似乎是一个同步问题,我将以某种方式解决.

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. This seems to be a synchronizing Problem and i will figure that out somehow.

无论如何,谢谢您的帮助和时间!

Anyways, thank you for your help and time!

这篇关于猫鼬填充返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆