简体   繁体   中英

How to pass data with Mongoose to a global variable?

My relevant code is split into three files:

user.server.model.js:

    var UserSchema = new Schema({
        ...            
        devices: []
    });

mongoose.model('User', UserSchema);

users.server.controller.js:

var User = require('mongoose').model('User') 

var devices = 123;

exports.getDevices = function(req, res, next) { 
    User.findOne({
            _id: req.user.id
        },
        function(err, user) {
            if (err) {
                return next(err);
            }
            else {
                devices = req.user.devices;
                res.json(devices)                       
            }
        }
    )
}

exports.devices = devices;

index.server.controller.js:

var users = require('../../app/controllers/users.server.controller')

exports.render = function(req, res) {   
    res.render('index', {
        title: 'MEAN MVC',
        user: req.user ? req.user.name: '',
        device: users.devices
    });
};

I am using node.js, mongoose, mongodb, express, embeddedjs.

What I need to do is to get the devices array and pass it down one way or other to my index page where can I then handle it there with ejs. As I am not experienced in JavaScript, I did not find a clear solution, so I decided to pass the data to a global variable 'devices' , then pass it to index page controller.

Now the problem I am facing is that getDevices function does not change the global variable 'devices' . What I know for sure, is that res.json(devices) gives a correct result of devices array in plain json and that the default value (123) of the global variable 'devices' is passed down to my index page controller and rendered in page.

Any other suggestion how my need should be solved is greatly appreciated.

Thank you very much.

devices isn't a global variable: it's only accessible from within the file that contains it, in your case users.server.controller.js .

You need to export devices , just like you do with the getDevices method. In users.server.controller.js , do exports.devices = 123 and exports.devices = req.user.devices . Then, users.devices will work correctly in index.server.controller.js .

EDIT: However returning a value from a method like that is not a very good/elegant solution, it seems like getDevices should be returning the devices array. If the reason you decided to do it like this is because Mongoose's findOne returns the result in a callback, consider using another callback at the getDevices level or look into promises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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