Handling relationships in Mongo and Sails?

*爱你&永不变心* 提交于 2019-12-11 04:55:29

问题


I'm having a bit of a nightmare at the moment trying to figure out relationships in Mongo and Sailsjs.

At the moment, I have 3 models. User, Photo and Category:

User

  attributes: {
    username  : { type: 'string', unique: true },
    first     : { type: 'string', required: true },
    last      : { type: 'string', required: true },
    email     : { type: 'email',  unique: true },
    photos    : { collection: 'photo', via: 'user' },
    passports : { collection: 'passport', via: 'user' },
    shareNum  : { type: 'integer'}
  }

Photo

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

Category

  attributes: {
    photo       : { model: 'photo' },
    category    : { type: 'string'}
  }

As it stands, when a user uploads a Photo, I have linked the User and Photo models together, and my code takes the User ID from the header and it shows up in my Photo collection as an ObjectID which confirms to me that the 2 are now linked and related.

What I am now trying to do is add a Category to my Photo. The Category field is to be stored as an array, as a Photo can have multiple Categories.

What I want to do here is store the preset Categories in the Category collection as separate documents. Lets say we call one Dog and one Cat for now. When a user uploads a photo with the category array containing Dog and Cat, it will store their ObjectID's in the Photos collection.

I've tried to do the following, but all I can get it to do is to store the actual array values, rather than the associate ObjectID

Photo

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

Category

  attributes: {
    photo       : { model: 'photo' },
    category    : { type: 'string'},
    categories   : { collection: 'photo', via: 'categories' }
  }

I am attempting to do this using the following query:

    Photo.create({caption :'var', user : '55cdeb6059798a3f424aa0cb', fid : 'rar', category : ['dog','cat']}).exec(function(err,created) {
console.log('test');
});

The query works returning undefined and then test. In my database, I have the array, but it stores the string of cat and dog as an array, rather than the ID they link to in the Category collection.

Do I have to do something first to get the ID for dog and cat?

来源:https://stackoverflow.com/questions/32118270/handling-relationships-in-mongo-and-sails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!