Node.js Mongo db查询查找不';不显示数组结果

Node.js Mongo db查询查找不';不显示数组结果,node.js,mongodb,Node.js,Mongodb,我是node js/Express开发的新手。我开发了一个工作正常的登录服务。现在我需要升级这个服务,并使用login的用户名对其他mongo文档进行查询,并将数组结果检索到json消息中 我已经使用findOne编写了一个查询,并且可以工作,但是如果我使用queryfind,那么数组是空的 router.post('/login', function(req, res) { User.findOne({ username: req.body.username}, function(err, u

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

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}});
    });
});
});
这是my db的一个示例:

{
"_id" : ObjectId("5c1e2586d695741104f724f1"),
"demographics" : {
    "farmSize" : "100",
    "crops" : "Forage Crops",
    "liveStock" : "YES",
    "precisionFarming" : "YES",
    "currentTire" : "Dealer"
},
"farmId" : "mAje06ni",
"companyName" : "xxxx",
"firstname" : "xxxxx",
"address" : "xxxxxx",
"city" : "Roma",
"state" : "Italy",
"postalcode" : "xxxxx",
"country" : "Italia",
"telephone" : "xxxxxxxxx",
"email" : "xxxxxxxxxx",
"lat" : 41.7476267,
"lon" : 12.3648812,
"__v" : 0
}

/* 4 */
{
"_id" : ObjectId("5c1e4f2dbc87ba0730969f07"),
"demographics" : {
    "farmSize" : "200",
    "crops" : "Forage Crops",
    "liveStock" : "YES",
    "precisionFarming" : "YES",
    "currentTire" : "Special Tire"
},
"farmId" : "mAje06ni",
"companyName" : "xxxxxx",
"firstname" : "xxxxxx",
"address" : "xxxxxxxxx",
"city" : "Roma",
"state" : "Italy",
"postalcode" : "00100",
"country" : "Italy",
"telephone" : "xxxxxx",
"email" : "xxxxxxxxxxxxxx",
"timestamp" : ISODate("2018-10-16T16:00:00.000Z"),
"lat" : 41.752784,
"lon" : 12.368663,
"__v" : 0
}
我需要数组结果来识别你的农场。为什么我的结果是空的?
谢谢

所以问题在于您在哪里初始化阵列,请将其放在查找之前。我编辑了你的代码,看看吧

另外,您的主要问题是场是一个数组,因此
场。\u 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}});
    });
});
});

假设您使用的是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);
    }

你能给我们看看你的db的样品吗?你可以清空这些字段。也不是
console.log(Farm.find({farmId:user.farmId}))
do
console.logs(farms)
我已经用db示例更新了我的代码你在使用Mongoose吗?嗨,Muhad,我尝试过你的代码,数组结果总是空的,如果我使用findOne,我有一个结果是正确的;但是,您无法访问场。\u id因为它是一个数组,所以您可以做的一件事是循环通过它并添加到数组中,我将立即更新我的答案。是的,现在可以,但使用find()而不是findOne()。谢谢你的帮助很抱歉我想把它改成
find
我现在就把它修好了你好,我用的是猫鼬。我已经试过你的代码了。toArray不是Mongoose的函数