如何使用Mongoose和Express为用户分配帖子

时间:2016-12-24 08:16:40

标签: node.js mongodb

我目前担心如何在用户在网站上创建帖子时为其分配帖子。所以基本上我想让一个登录用户创建一个简历,然后将该简历分配给该登录用户作为架构中的created_by。我有点排序,但我不知道创建简历并将登录用户分配给它。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
var moment = require('moment');
var id = require('../helpers/generator');
let beautifyUnique = require('mongoose-beautiful-unique-validation');


const ResumeSchema = new Schema({
  _id: {
    type: String,
    default: id.generate()
  },
  title: {
    type: String,
    required: true
  },
  creator: {
    type: ObjectId,
    ref: "User"
  },
  description: {
    type: String,
    default: "No description provided."
  },
  company_reviews: {
    name: {
      type: String,
      default: "RSW"
    },
    review: {
      type: String,
      default: "asodsodo"
    },
    rating: {
      type: String,
      default: "10/10"
    }
  },
  employee_reviews: {
    name: {
      type: String,
      default: "Doge Dog"
    },
    company: {
      type: String,
      default: "RSW"
    },
    review: {
      type: String,
      default: "blah blah"
    },
    rating: {
      type: String,
      default: "10/10"
    }
  },
  createdAt: {
    type: String,
    default: moment(new Date()).format("MMM DD, YYYY") // "Sun, 3PM"
  }
});

var Resume = mongoose.model('Resume', ResumeSchema);
module.exports = Resume;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var moment = require('moment');
var bcrypt = require('bcrypt');
var id = require('../../helpers/generator');
let beautifyUnique = require('mongoose-beautiful-unique-validation');


const UserSchema = new Schema({
    _id: {
        type: String,
        default: id.generate()
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    accountType: {
        type: String,
        enum: ['Alphaneer', 'Administrator', 'Support', 'PRO'],
        default: 'Alphaneer'
    },
    email: {
        type: String,
        required: true,
        trim: true
    },
    username: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    bio: {
        type: String,
        default: "No bio provided."
    },
    password: {
        type: String,
        required: true
    },
    createdAt: {
        type: String,
        default: moment(new Date()).format("MMM DD, YYYY") // "Sun, 3PM 17"
    }
});

// authenticate input against content from database. BLOODY HELL ITS A MESS
UserSchema.statics.authenticate = function(email, password, callback) {
    User.findOne({
            email: email
        })
        .exec(function(err, user) {
            if (err) {
                return callback(err);
            }
            bcrypt.compare(password, user.password, function(err, result) {
                if (result === true) {
                    return callback(null, user)
                } else {
                    return callback();
                }
            })
        })
}

UserSchema.pre('save', function(next) {
    var user = this;
    bcrypt.hash(user.password, 10, function(err, hash) {
        if (err) throw err;
        user.password = hash;
        console.log("LOG: Password hashed & user saved.");
        next();
    });
});

var User = mongoose.model('User', UserSchema);

module.exports = User;

我想在这里创建一个Resume作为登录用户

// POST /dashboard/resume/create
router.post('/resume/create', (req, res, next) => {
  Resume.create(req.body, (err, resume) => {
    if (err) {
      var err = new Error("Error:" + err);
      err.status = 404;
      next(err);
    } else {
      return res.redirect('/dashboard');
    }
  })
});

我在注册用户时也会创建一个Resume。一种受欢迎的东西

// POST /register
router.post('/', (req, res, next) => {
  var data = {
    firstName: req.body.fName,
    lastName: req.body.lName,
    username: req.body.username,
    email: req.body.email,
    password: req.body.password,
    bio: req.body.bio
  };
  User.create(data, (err, user) => {
    if (err) {
      throw err;
    }
    var resume = {
      title: "Welcome to NAME!"
    }
    Resume.create(resume, (err, resume) => {
      if (err) throw err;
      return res.redirect('/');
    });
  });
});

感谢任何帮助,如果没有意义,我也可以做一些进一步的解释:)

1 个答案:

答案 0 :(得分:1)

我想到的一个解决方案就是将简历的引用保留在用户模式中,每当有“POST / resume / create”时,首先将恢复对象保存在Resume模式中,然后使用简历参考。由于您的用户已登录,因此您应该将登录的用户详细信息保存在req.user中的某些位置。部分代码应该是这样的:

//add this code to your user Schema 
 resume: {
     type: Schema.objectId,
     ref: 'Resume'
 }

您应修改注册功能以保存简历并更新用户模型中的简历引用。

// POST /dashboard/resume/create
router.post('/resume/create', (req, res, next) => {
  Resume.create(req.body, (err, resume) => {
    if (err) {
      var err = new Error("Error:" + err);
      err.status = 404;
      next(err);
    } else {
      //I am assuming that you have saved your resume and getting the saved object in `resume`, now update the logged in user in req.user
    var user = req.user;
    user.resume = resume._id;
 //save the updated user
    user.save((error, user) => {
      if(error) {
        //handle error
      } else {
       //you have saved the user with resume ref now.
        return res.redirect('/dashboard');
      }
    })
    }
  })
});