Join collection di node js

saya punya 2 collections yaitu forum dan user.

var ForumSchema = mongoose.Schema({
	title: {
		type: String,
		require: true
	},
	slug: {
		type: String,
	},
	image: {
		type: String,
	},
	desc: {
		type: String,
		require: true
	},
	user: {
		type: String,
	},
	date: {
		type: String
	}
})

var UserSchema = new mongoose.Schema({
	nama: {
		type: String,
		require: true,
	},
	username: {
		type: String,
		require: true,
		unique: true,
		lowercase: true,
	},
	email: {
		type: String,
		require: true,
		unique: true,
		lowercase: true,
	},
	password: {
		type: String,
		require: true,
	},
	avatar: {
		type: String,
	},
	joindate: {
		type: String,
	}
});

lalu pada halaman index dari forumnya saya akan menampilkan data forum beserta user yang submit forumnya. pada collection forum ada user yang berisi _id dari user. dan saya coba tampilkan seperti ini kok saya panggil di view ejs dengan "user.nama" kok error "Cannot read property 'nama' of null"

router.get('/', function(req, res){
	Forum.find(function(err, forum){
		User.findOne({ _id: forum.user }, function(err, user){
			res.render('forum/index', {
				judul: 'Forum',
				css: '/public/css/forum.css',
				forum: forum,
				user: user
			});
		});
	});
});

saya coba console.log dari forum.user hasilnya undefined

router.get('/', function(req, res){
	Forum.find(function(err, forum){
                console.log(forum.user); //yang di console log
		User.findOne({ _id: forum.user }, function(err, user){
			res.render('forum/index', {
				judul: 'Forum',
				css: '/public/css/forum.css',
				forum: forum,
				user: user
			});
		});
	});
});

jadi inti dari pertanyaannya adalah gimana cara mengambil user di collection forum untuk di cocokan dengan _id dari collection user.

avatar tonisuwendi
@tonisuwendi

169 Kontribusi 36 Poin

Diperbarui 4 tahun yang lalu

1 Jawaban:

Jawaban Terpilih

Di forumSchema untuk usernya type: mongoose.Types.ObjectsId, dan ref: 'User'

<pre> var ForumSchema = mongoose.Schema({ title: { type: String, require: true }, slug: { type: String, }, image: { type: String, }, desc: { type: String, require: true }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', }, date: { type: String } }) </pre>

pada routernya di buat populate

<pre> router.get('/', function(req, res){ Forum.find({}).populate('user').sort('-_id').exec(function(err, forum){ res.render('forum/index', { judul: 'Forum', css: '/public/css/forum.css', forum: forum, }); }); }); </pre>

pada view ejsnya di panggil seperti ini

<pre> &lt;%= forum.user.nama %&gt; </pre>

avatar tonisuwendi
@tonisuwendi

169 Kontribusi 36 Poin

Dipost 4 tahun yang lalu

Login untuk ikut Jawaban