Answer the question
In order to leave comments, you need to log in
How to populate (join) two collections in Mongoose?
You need to join two collections into a third one and fetch data via .populate() (MongooseJS) from this third collection. According to this manual, I figured out how to implement it and the method is quite satisfied. There was a small problem, or rather the specifics of the problem that I solve.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var youTubeSchema = Schema({
id: String,
_trailer: { type: Schema.Types.ObjectId, ref: 'Trailer' }
});
var postersSchema = Schema({
posters: String,
_trailer : { type: Schema.Types.ObjectId, ref: 'Trailer' }
});
var trailerSchema = Schema({
timestamp: String,
_youtube : { type: Schema.Types.ObjectId, ref: 'YouTube' },
_posters : { type: Schema.Types.ObjectId, ref: 'Posters' }
});
var YouTube = mongoose.model('YouTube', youTubeSchema);
var Posters = mongoose.model('Posters', postersSchema);
var Trailer = mongoose.model('Trailer', trailerSchema);
var trailer = new Trailer({
timestamp: new Date()
});
trailer.save(function (err) {
if (err) return handleError(err);
var youtube = new YouTube({
id: "rTCxSguAmjQ",
_trailer: trailer._id
});
youtube.save(function (err) {
if (err) return handleError(err);
});
var posters = new Posters({
posters: "4j3h34hg34ygyu34gkj43h.jpg",
_trailer: trailer._id
});
posters.save(function (err) {
if (err) return handleError(err);
});
});
YouTube
.findOne({ _id: '5502a5cf57e8ca2c0b58962d' })
.populate('_trailers')
.exec(function (err, trailer) {
if (err) return handleError(err);
console.log(trailer._trailer);
});
Trailer.update({_id: '5502a5cf57e8ca2c0b58962d'}, {_youtube: youtube._id, _posters: posters._id}, {upsert: true}, function (err) {
if (err) return handleError(err);
});
Answer the question
In order to leave comments, you need to log in
I don't fully understand the question, but I'll try to answer the way I understand it.
There are trailers that have a YouTube video ID and a path to the poster (jpg).
In fact, the scheme itself is not built correctly.
What are the separate collections of YouTube and Posters used for?
The main document is the trailer, it has one YouTube link and one poster, but in theory it could have more.
Youtube link and poster address cannot have more than one trailer (can't belong to more than one trailer), moreover they are always unique and tied to a trailer.
You can make ONE nested schema instead of three, without DBref references.
var trailerSchema = Schema({
timestamp: String,
youtube : String
poster : String
});
var trailerSchema = Schema({
timestamp: String,
youtube : [{name: String, url: String}]
posters : [{name: String, url: String}]
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question