MongoDB NodeJS返回子文档 [英] MongoDB NodeJS Return subdocument

查看:83
本文介绍了MongoDB NodeJS返回子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回与查询字段匹配的子文档.我只想返回与用户匹配的PIN,该PIN保留在帐户集中.这是我到目前为止所掌握的.

I'm trying to return a subdocument that matches the query fields. I just want to return the PIN that matches the user, which is held in the account collection. This is what I've got so far.

    router.post('/SelectUser', async(req, res) =>{
        try{
            const acc = await Account.findOne({"Email": req.body.Email});
            if(!acc) throw Error('Email not found');
    
            var user = await Account.findOne({"Users.Username":req.body.User.Username},{Users:{PIN:1}});
}

这将输出与帐户关联的所有PIN,这不是我想要的.这是我正在使用的模式和模型:

This outputs all the PINs associated with an account, which isn't what I want. Here are the Schemas and Models that I'm using:

帐户:

const User = require('../Models/UserData');

const AccountSchema = new Schema({
    // Email linked to this account
    Email:{
        type:String,
        unique:true,
        required:true,
        index:true
    },
    // Password for the account
    Password:{
        type : String,
        required : true
    },
    // Users on this account
    Users:{
        type:[User],
        required:true
    }
});

module.exports = mongoose.model('Account', AccountSchema);
            

用户:

const UserSchema = new Schema({
    // Name of the user
    Username:{
        type:String,
        required:true,
        unique:true
    },
    // PIN for each user
    PIN:{
        type:Number,
        require:true
    }

});

module.exports = UserSchema;

推荐答案

您尝试做的事情在您的应用中非常简单(例如,在 findOne 之后的JS代码),但是如果您确实如此想要在mongodb中做到这一点,那么您将需要使用聚合.将您的代码更改为:

What you're trying to do would be pretty trivial in your app (i.e JS code after findOne), but if you really want to do it in mongodb, then you will need to use aggregation. Change your code to:

const username = req.body.User.Username;
const user = await Account.aggregate([
    {
        $match: {
            "Users.Username": username
        }
    },
    {
        "$project": {
            _id: false,
            USER: {
                $filter: {
                    input: "$Users",
                    as: "users",
                    cond: {
                        $eq: [
                            "$$users.Username",
                            username
                        ]
                    }
                }
            }
        }
    },
    {
        "$unwind": "$USER"
    },
    {
        "$project": {
            USER_PIN: "$USER.PIN"
        }
    }
]);

if(user.length){
    console.log(user[0].USER_PIN)
}else{
    console.log('Username not found')
}

以下是实际的汇总查询,供您使用: https://mongoplayground.net/p/o-xTTa8R42w

Here is the actual aggregation query for you to play around with: https://mongoplayground.net/p/o-xTTa8R42w

这篇关于MongoDB NodeJS返回子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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