N
N
Nick Nesterov2016-03-23 14:01:01
MongoDB
Nick Nesterov, 2016-03-23 14:01:01

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' }
});

I need to save the story so that it has its own user, and the user has its own array of story IDs. I'm most likely doing it wrong, when saving the story, I put the _id user-a in the story:
var story = new Story({
  name: 'some name',
  user: user._id
});
event.save();

Naturally, the story is saved with the user id, but for this user, the id or object of this story does not appear in the array.
user: {
   name: 'User Name',
   stories: [] //тут пусто
 }

What am I doing wrong? How to save objects with links correctly?
Or after saving the child object, you need to update the parent

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitrii Solovev, 2016-03-24
@njnesterov

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.

B
bromzh, 2016-03-23
@bromzh

What am I doing wrong?

You use mongo where you don't need it.
Take a relational database. In the name itself there is a hint that such databases are well suited for storing objects with relationships.
What's the point of taking monga and trying to build a relational database style architecture? What prevents to store story in the field of the document of the user?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question