如何在mongodb中移动对象数组?

时间:2018-12-18 19:20:02

标签: node.js mongodb

我已经在nodejs中创建了两个模型,分别是:UserAuth

在用户模型中将存储用户名和作为Auth模型引用的身份验证对象数组。

在Auth模型中,将存储JWT生成的令牌和令牌的创建日期...

规则: 每个用户可以有多个身份验证令牌,但是每个令牌在令牌过期后将是唯一的,它将在数据库中中止,但是创建日期应该保留。

我怎么了?

1)我在Array中存在转换问题。

2)我不知道如何通过身份验证令牌和特定的用户名来遍历此对象数组。

const mongoose = require('mongoose');

class AuthModel {
    createSchema(){
        const authSchema = new mongoose.Schema({
            token: {
                type:     String,
                unique:   true,
                required: true
            },
            createAt: {
                type:    Date,
                default: Date.now
            }
        });

        return authSchema;
    }
}

module.exports = mongoose.model('AuthModel', new AuthModel().createSchema());

const mongoose = require('mongoose');

class UserModel {
    createSchema(){
        const userSchema = new mongoose.Schema({
            username: {
                type:     String,
                unique:   true,
                required: true
            },
            createdAt: {
                type:    Date,
                default: Date.now
            },
            auth: [{
                type: mongoose.Schema.Types.ObjectId,
                ref: 'AuthModel',
                required: true,
            }]
        });

        return userSchema;
    }
}

module.exports = mongoose.model('UserModel', new UserModel().createSchema());

1 个答案:

答案 0 :(得分:0)

   1: //define embedded schema    
    const authSchema = new mongoose.Schema({
                  type: mongoose.Schema.Types.ObjectId,
                    ref: 'AuthModel',
                    required: true,
       });
      const userSchema = new mongoose.Schema({
                username: {
                    type:     String,
                    unique:   true,
                    required: true
                },
                createdAt: {
                    type:    Date,
                    default: Date.now
                },
                auth: [authSchema]   // add embedded schema here  
            });
 2 .  When you fetch userModel, you will be required to populate( mongoose function) auth model