How to preserve uniqueness based on a specific fieldin array Without using a unique index

I have such a document.

[{
    "_id" : ObjectId("aaa"),
    "host": "host1",
    "artData": [
    {
        "aid": "56004721",
        "accessMin": NumberLong(1481862180
    },
    {
        "aid": "56010082",
        "accessMin": NumberLong(1481861880)
    },
    {
        "aid": "55998802",
        "accessMin": NumberLong(1481861880)
    }
    ]
},
{
    "_id" : ObjectId("bbb"),
    "host": "host2",
    "artData": [
    {
        "aid": "55922560",
        "accessMin": NumberLong(1481862000)
    },
    {
        "aid": "55922558",
        "accessMin": NumberLong(1481861880)
    },
    {
        "aid": "55940094",
        "accessMin": NumberLong(1481861760)
    }
    ]
}]

when updating any document, duplicate "help" should not be added to the array again. One of the options I got is to use a unique index in the artData.aid field. But building indices are not preferred, as I will not need it as required. Is there any way to solve this?

+4
source share
2 answers

Option 1: Use when designing a schema for this document unique:true. eg:

var newSchema = new Schema({
 artData: [
    {
        aid: { type: String, unique: true },
        accessMin: Number
    }]
});
module.exports = mongoose.model('newSchema', newSchema );

Option 2: Link to a link to avoid duplication

+3

, :

{ "artData.aid": 1 }

, , -

  • , artData's, aid
  • , .
  • ,
  • 2

, 1 , . , , , . , 1 , , , = (.

,

0

Source: https://habr.com/ru/post/1663916/


All Articles