How to store array of ObjectID's in Mongo with

2019-08-12 06:52发布

After my initial question: Handling relationships in Mongo and Sails?

I managed to use this approach, however I now need to resolve this the way I originally thought. For example, I have my Photo and Category models & collections, but now my category also contains addresses and business details.

In my Photo model I have the following:

attributes: {
    caption  : { type  : 'string' }, 
    fid      : { type  : 'string' },
    user     : { model : 'user' },
    categories : { model : 'category', type : 'array'}
  }

In my Category model I have the following:

  attributes: {
    photo       : { model: 'photo' },
    category    : { type: 'string'},
    address     : { type: 'string'},
    phone       : { type: 'integer'},

    //Foreign Keys
    categories   : { collection: 'photo', via: 'categories', type : 'integer'}
  }

Now I can get the categories in the Photo collection to show as an ObjectID if I removed the type array and just send a single ObjectID of a category, however in my case, a photo can have more than one Category.

If I try sending an array of ObjectID's in my query, they just show up in the database as a String array. Is there anyway I get store these as an array of ObjectID's instead?

1条回答
贼婆χ
2楼-- · 2019-08-12 07:39

Basically it's many to many relationship. You can use Waterline scheme like this:

Photo Model

attributes: {
  caption  : { type  : 'string' }, 
  fid      : { type  : 'string' },
  user     : { model : 'user' },
  categories : { collection : 'category', via : 'photos'}
}

Category Model

attributes: {
  photos      : { collection: 'photo', via: 'categories' },
  category    : { type: 'string'},
  address     : { type: 'string'},
  phone       : { type: 'integer'},
}
查看更多
登录 后发表回答