Many-many association on the same model (like user_user) doesn't work
FedjaVitko opened this issue · comments
The document inside the user_user collection only contains one user field. Should it not contain two user fields?
Steps to replicate the issue:
- Create two users. (POST /user)
- Add the second user as a friend of the first one. (POST /user/{firstUserId}/user) { childId: secondUserId })
- Get the friends of the firstUser. (GET /user/{firstUserId}/user)
- The response object is empty. No friends get returned.
Hi @TheoVitkovskiy, I've been super busy lately but I will try to look into this. In the meantime, would you mind posting your code for the user
model?
Hi @TheoVitkovskiy, I've been super busy lately but I will try to look into this. In the meantime, would you mind posting your code for the
user
model?
Hi @JKHeadley, for this I just used the example from the documentation https://resthapi.com/docs/associations.html. You find it under the Linking Models section. In my specific use case I'm doing the same, but with book sections. Here is my code for the section
model.
Hi @TheoVitkovskiy, I've been super busy lately but I will try to look into this. In the meantime, would you mind posting your code for the
user
model?Hi @JKHeadley, for this I just used the example from the documentation https://resthapi.com/docs/associations.html. You find it under the Linking Models section. In my specific use case I'm doing the same, but with book sections. Here is my code for the
section
model.
function(mongoose) {
const modelName = 'section';
const Types = mongoose.Schema.Types;
const Schema = new mongoose.Schema({
book: {
type: Types.ObjectId,
ref: "book"
},
startCounter: {
type: Types.Number,
required: true
},
endCounter: {
type: Types.Number,
required: true
}
});
Schema.statics = {
collectionName: modelName,
routeOptions: {
associations: {
book: {
type: "MANY_ONE",
model: "book"
},
verses: {
type: "MANY_MANY",
model: "verse"
},
sections: {
type: "MANY_MANY",
model: "section",
alias: "section",
linkingModel: "section_section"
}
}
}
};
return Schema;
}
I found the same issue.
Interestingly, when I refer to your example above
try a
GET /user/{secondUserId}/user
In my case, this is where I found the association but from secondUserId to secondUserId.
That looks like a bug to me.
So, interesting further discovery:
It works when you add embedAssociation: true,
then it adds the association for
GET /user/{secondUserId}/user
and for
GET /user/{firstUserId}/user
to the respective association partner.
Just one note:
API-wise I would have exprected the association to be directed
I.e. only firstUserId -> secondUserId
but it generates an undirected association
firstUserId <-> secondUserId
Maybe I missed that from the documentation ;-)
@OliS76 Thanks for the input! This will be the first issue I'll look into when I get a chance.