0

模型.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
});
}

我在 blogpostschema 中的 userid 字段没有在数据库中创建?我尝试使用各种方法进行引用,但不起作用。谁能帮我吗!

可能我认为某些人认为填充方法可能出错了。

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 
  }
4

0 回答 0