Mongo DB查询查找不显示数组结果

时间:2018-12-22 15:23:03

标签: node.js mongodb

我是Node js / Express开发的新手。我开发了一个可以正常运行的登录服务。现在,我需要升级此服务,并使用登录用户名对其他mongo文档进行查询,并将数组结果检索到json消息中 我已经使用findOne编写了一个查询,并且可以正常工作,但是如果我使用查询,则发现数组为空

function laroyale(){

var feuille = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var ligne   = feuille.getLastRow();
var data    = ligne.getValue ();

这是我的数据库的示例:

router.post('/login', function(req, res) {
User.findOne({ username: req.body.username}, function(err, user) {
    if (err){
        return res.status(500).send('Error on the server.');
    }
    if (!user){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is not associated with any account.'}});
    }
    var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
    //if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
    if (!passwordIsValid){
        return res.status(401).send({status: 'ko', error: {msg:'Authentication failed. Wrong password.',auth: false, token: null}});
    }
    // Make sure the user has been verified
    if (!user.isVerified){
        return res.status(401).send({status: 'ko', error: {type: 'not-verified', msg: 'Your account has not been verified.'}});
    }
    if (!user.statusUser){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is blocked by Admin'}});
    }
    // if user is found and password is valid
    // create a token
    var token = jwt.sign({ id: user._id }, config.secret, {
      expiresIn: 86400 // expires in 24 hours
    });

    // inserimento farm id //
    Farm.find({ farmId: user.farmId}, (err, farms) => {
        console.log(Farm.find({farmId:user.farmId}));
        var identify_farm = [];
        if (err) {
            //return res.status(400).send({ status: 'ko', data: {msg: err.message }});
            var txt = err.message;
            identify_farm.push(txt);
        }
        if (!farms) {
            //return res.status(404).send({ status: 'ko', data: {msg: 'Farm not found.'}});
            identify_farm.push('Farm not found.');
        }
        if (farms) {
            identify_farm.push(farms._id);
        }
    // inserimento farm id //

    // return the information including token as JSON
    req.session.user = user;
    res.status(200).send({status: 'ok', data: {auth: true, token: token, farmId: user.farmId, roles: user.roles, id_utente: user._id, identify_farms: identify_farm}});
    });
});
});

我需要将数组结果放入identify_farms。为什么我的结果为空? 谢谢

2 个答案:

答案 0 :(得分:1)

所以问题在于初始化数组的位置,将其放在发现之前。我编辑了您的代码,看看吧。

另外,您的主要问题是场是一个数组,因此farms._id不存在。 find将查找一个数组,如果您只想查找1,则使用findOne

router.post('/login', function(req, res) {
User.findOne({ username: req.body.username}, function(err, user) {
    if (err){
        return res.status(500).send('Error on the server.');
    }
    if (!user){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is not associated with any account.'}});
    }
    var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
    //if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
    if (!passwordIsValid){
        return res.status(401).send({status: 'ko', error: {msg:'Authentication failed. Wrong password.',auth: false, token: null}});
    }
    // Make sure the user has been verified
    if (!user.isVerified){
        return res.status(401).send({status: 'ko', error: {type: 'not-verified', msg: 'Your account has not been verified.'}});
    }
    if (!user.statusUser){
        return res.status(401).send({status: 'ko', error: {msg: 'The username ' + req.body.username + ' is blocked by Admin'}});
    }
    // if user is found and password is valid
    // create a token
    var token = jwt.sign({ id: user._id }, config.secret, {
      expiresIn: 86400 // expires in 24 hours
    });

    // inserimento farm id //
    Farm.find({ farmId: user.farmId}, (err, farms) => {
        var identify_farm = [];

        farms.forEach(function(farm){
           console.log(farm);
           if (farm) {
            identify_farm.push(farm._id);
           }
        })

    // inserimento farm id //

    // return the information including token as JSON
    req.session.user = user;
    res.status(200).send({status: 'ok', data: {auth: true, token: token, farmId: user.farmId, roles: user.roles, id_utente: user._id, identify_farms: identify_farm}});
    });
});
});

答案 1 :(得分:0)

假设您使用的是MongoDB驱动程序而不是Mongoose,collection.find返回一个游标而不是一个数组。为了返回文档,您需要像这样

在其上调用toArray()方法
Farm.find({ farmId: user.farmId}).toArray((err, farms) => {
    console.log(Farm.find({farmId:user.farmId}));
    var identify_farm = [];
    if (err) {
        //return res.status(400).send({ status: 'ko', data: {msg: err.message }});
        var txt = err.message;
        identify_farm.push(txt);
    }
    if (!farms) {
        //return res.status(404).send({ status: 'ko', data: {msg: 'Farm not found.'}});
        identify_farm.push('Farm not found.');
    }
    if (farms) {
        identify_farm.push(farms._id);
    }