首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在mongodb中移动对象数组?

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

Stack Overflow用户
提问于 2018-12-19 03:20:02
回答 1查看 36关注 0票数 0

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

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

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

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

我的问题是什么?

数组1)我在中遇到强制转换问题。

2)我不知道如何遍历这个对象数组,从auth令牌和特定的用户名开始。

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());
EN

回答 1

Stack Overflow用户

发布于 2018-12-19 04:54:04

   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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53839713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档