Model.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
var uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcrypt')
const UserSchema = new Schema({
username: {
type: String,
required: [true, 'please provide username'],
unique: true
},
password: {
type: String,
required: [true, 'please provide password'],
}
});
UserSchema.plugin(uniqueValidator);
UserSchema.pre('save', function(next){
const user = this
bcrypt.hash(user.password, 10, (error, hash) => {
user.password = hash
next()
})
})
const BlogPostSchema = new Schema({
title: String,
body: String,
// username: String,
userid: {
type: mongoose.Schema.Types.ObjectId, // suppose to be a valid mongodb object id. mongodb has specific ids for each doc and they have to be in a valid format
ref: "User", // reference User collection
},
datePosted:{ /* can declare property type with an object like this because we need 'default' */
type: Date,
default: new Date()
},
// postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
image: String
});
// export model
const User = mongoose.model('User',UserSchema);
const BlogPost =mongoose.model('BlogPost',BlogPostSchema);
module.exports = {User: User, BlogPost: BlogPost}
getPost.js
const { BlogPost } = require('../models/Model')
module.exports = async (req,res)=>{
const blogpost = await BlogPost.findById(req.params.id).populate('userid');
res.render('post',{
blogpost
});
}
My userid field in blogpostschema is not getting created in the database? I tried referencing using various methods but won't work. Can anyone help me out!
May be i think somethink may have gonne wrong with the populate method.
userid: {
type: mongoose.Schema.Types.ObjectId, // suppose to be a valid mongodb object id. mongodb has specific ids for each doc and they have to be in a valid format
ref: "User", // reference User collection
}