【问题标题】:Mongoose Schemas RelationshipsMongoose 模式关系
【发布时间】:2022-01-04 09:18:16
【问题描述】:

我有两个架构,第一个是客户端,它有客户端 ID 和名称:

下面是架构代码:

const ClientSchema = new mongoose.Schema({

_id: Number,

org_name: {
    type: String,
    required: true,
    trim: true,
},

});

另一个模式是用户,它有对象 id 和用户名:

下面是架构代码:

const User = mongoose.model('user', {

username: {
    type: String,
    required: true,
    trim: true
},

});

现在,我想为每个用户添加客户端模式 ID。我该怎么做?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我们可以通过修改 clientSchema 模型来包含一个类型设置为 mongoose.Schema.Types.ObjectId 的用户来解决这个问题。

    用户架构是:

    
    username: {
        type: String,
        required: true,
        trim: true
    },
    });
    

    修改过的clientSchema

      const ClientSchema = new mongoose.Schema({
        
        _id: Number,
        
        org_name: {
            type: String,
            required: true,
            trim: true,
        },
        
            user:{ type: mongoose.Schema.Types.ObjectId,ref:'user'},
        
        });
    

    保存用户:

    const user= new User({
           'myusername'
        });
    
    const result = await user.save();
    

    保存客户端架构:

    const clientschema= new clientSchema({
            'myorg_name',
            user // user object
        });
    
    const clientresult = await clientschema.save();
    

    现在检查 mongodb 中的 clientsschema 文档,您将看到用户对象 ID。

    参考以下链接

    https://vegibit.com/mongoose-relationships-tutorial/

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-07-04
    • 2017-10-23
    • 1970-01-01
    • 2017-10-27
    • 2013-04-13
    • 2011-12-18
    • 2019-02-26
    • 2019-08-11
    • 2012-02-03
    相关资源
    最近更新 更多