You want to avoid double stitching because it means twice as much to support, and because Mongo does not support transactions, it creates the possibility of semi-linked data if you expect it to be connected twice. In doing so, I revise your circuits like this:
var like = { itemid: { type: Schema.ObjectId, ref: 'Item'} , rating: Number }; var UserSchema = new Schema({ username : { type: String, required: true, index: { unique: true } , likes : [like] , dislikes : [like] }); UserSchema.index({ 'likes.itemid': 1 }); UserSchema.index({ 'dislikes.itemid': 1 }); var User = db.model('User', UserSchema); var ItemSchema = new Schema({ name: String }); var Item = db.model('Item', ItemSchema);
You can add likes or dislikes by saying:
var piano = new Item({name: 'Mason & Hamlin Baby Grand Piano' }); var Joe = new User({ username: 'Joe_Smith' }); Joe.likes.push({ itemid: piano._id, rating: 10 });
And when you want to find the things you like for the item:
User.find({ 'likes.itemid': piano._id }, function(err, userLikes) { ... });
And if none of this seems right to you, you can create a third collection ...
var UserSchema = new Schema({ username : { type: String, required: true, index: { unique: true } }); var User = db.model('User', UserSchema); var ItemSchema = new Schema({ name: String }); var Item = db.model('Item', ItemSchema); var LikesSchema = new Schema({ , userid: { type: Schema.ObjectId, ref: 'User'} , itemid: { type: Schema.ObjectId, ref: 'Item'} , rating: Number }); LikesSchema.index({ userid: 1, itemid: 1 }, { unique: true });
And in this case, it is probably easiest to make the rule that a positive rating is similar and a negative rating is not like.