Answer the question
In order to leave comments, you need to log in
How to correctly link two objects in Mongoose (MongoDB)?
Please tell me how to properly link two objects and how the process of linking two objects takes place.
Scheme:
var userSchema = new mongoose.Schema({
name: String,
stories: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = new mongoose.Schema({
name: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});
var story = new Story({
name: 'some name',
user: user._id
});
event.save();
user: {
name: 'User Name',
stories: [] //тут пусто
}
Answer the question
In order to leave comments, you need to log in
Firstly:
user: user._id - you need to save not the ID itself in the line, but mongoose ObjectID
So the scheme says "user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }"
But mongoose is a little smart, so it is possible to insert into the user the user himself, received when requesting from the database, and mongoose itself will add the correct ObjectID to the field.
It is important that user be exactly a mongoose object with all methods, and not a cleared plainobject.
Further, there is no foreign key in mongo, so such schemes as above are not desirable. Where the user refers to the story, and the story refers to the user. It turns out with any operations from the story, you need to update the user and vice versa. And this is 2 queries.
Here, either the story array is written to the user, or the creator is assigned to each story.
That is, either the parent has information about the child, or the child about the parent, BUT not both.
Which method is better depends on the specific situation, you need to look at what information and how to display it more often.
I would prefer to store a userid in each story. Leave user blank.
What am I doing wrong?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question