Reputation: 2269
Right now I'm really confused, do i need to push the objectId to both schemas or just save it in one schema?
My Schema
var CourseSchema = Schema({
title: String,
content: [{ type: Schema.Types.ObjectId, ref: 'Video'}],
});
var VideoSchema = Schema({
ownedBy: { type: Schema.Types.String, ref: 'Course'},
name: String
});
Schema objective
Let say I want to create a new video object and then store its ownedby
field to the a specific course objectId
Here's the code
app.get('/testData', function(req, res) {
Course.findOne({ title: "Testing Course" }, function(err, course) {
// Create a new video object
var video = new Video();
// store the object id into ownedby field, so that it belongs "Testing Course"
video.ownedBy = course._id;
video.title = newData.name;
// save it
video.save(function(err, vid) {
// Is it necessarily for me to push each video object to a course's content field?
course.content.push(vid._id);
});
});
});
If you read the comment, then you know what I'm facing, if not then let me explain it again
FindOne a specific title that match the Course's collection which is "Testing Course"
create a new video's object and then store it into video's
ownedBy
field
Save the Course's object and then push each video's id to its content.
There is no error or whatsoever, but it is kinda redundant for me to push both object id to both schemas
The real question is, is it really needed for me to push the object id to both schemas?
Upvotes: 0
Views: 80
Reputation: 606
You have to update both objects with references. That means that you also need to update Course object with video _id. Currently you are using findOne() which only returns document, not updating it.
Here is code example:
Course.findOne({ title: "Testing Course" }, function(err, course) {
if (err) return handleError(err);
var video = new Video();
video.ownedBy = course._id;
video.title = newData.name;
video.save(function(err, vid) {
if (err) return handleError(err);
course.content.push(vid._id);
course.save(function(err) {
if (err) return handleError(err);
});
});
});
Upvotes: 1