问题
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