如何为动态密钥字典定义mongoDB mongoose模式?

时间:2021-08-22 18:23:50

I have a MongoDB collection users where I want to store a dictionary with dynamic keys. I want users to look like this within MongoDB:

我有一个MongoDB集合用户,我想用动态密钥存储字典。我希望用户在MongoDB中看起来像这样:

{
    "_id": {
        "$oid": "5a9f5b3400e2f61a0c5f449b"
    },
    "profile": {
        "votes": {
            dynamicKey1Here: {
                constantKey: 'value',
                constantKey2: 'value2'
            },
            dynamicKey2Here: {
                constantKey: 'value',
                constantKey2: 'value2'
            },
            // more dynamic keys here...
    }
}

But I don't know how to define my schema. So far I have:

但我不知道如何定义我的架构。到目前为止我有:

const userSchema = new Schema({
    profile: {
        votes: {DynamicKeyEntry}
    }
});

So how would I define the schema for DynamicKeyEntry?

那么我如何定义DynamicKeyEntry的架构呢?

const DynamicKeyEntry = new Schema(
    // HOW DO I DEFINE DYNAMIC KEYS?
);

1 个解决方案

#1


0  

If you can use aray then it's better approach for storing and fetching data appropriately for ex:

如果你可以使用aray那么它是更好的方法来适当地存储和获取数据ex:

 votes: { type: Array }

Now you can store multiple objects in votes as your requirement

现在,您可以根据需要在投票中存储多个对象

#1


0  

If you can use aray then it's better approach for storing and fetching data appropriately for ex:

如果你可以使用aray那么它是更好的方法来适当地存储和获取数据ex:

 votes: { type: Array }

Now you can store multiple objects in votes as your requirement

现在,您可以根据需要在投票中存储多个对象