【问题标题】:MongoDB NodeJS Return subdocumentMongoDB NodeJS 返回子文档
【发布时间】:2021-06-17 21:36:09
【问题描述】:

我正在尝试返回与查询字段匹配的子文档。我只想返回与用户匹配的 PIN,该 PIN 保存在帐户集合中。这就是我目前所得到的。

    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,这不是我想要的。以下是我正在使用的模式和模型:

帐号:

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;

【问题讨论】:

  • 使用您当前的架构,无法将电子邮件与单个用户相关联,因此无法判断您尝试获取关联 PIN 的“用户”。
  • @CodyHaines 您将如何更改它们以使其成为可能?

标签: node.js arrays mongodb mongoose


【解决方案1】:

您尝试在您的应用程序中执行的操作非常简单(即findOne 之后的 JS 代码),但如果您真的想在 mongodb 中执行此操作,则需要使用聚合。将您的代码更改为:

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

【讨论】:

  • 非常感谢。正是我所追求的。它需要尽可能多地在 Node 中,因为我的应用程序不是用 JS 编写的,而是用虚幻引擎编写的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2020-07-03
  • 1970-01-01
  • 2023-04-05
  • 2021-12-03
  • 2016-04-26
  • 2016-01-21
相关资源
最近更新 更多