需要帮助将游戏保存到用户喜欢的游戏中

时间:2019-10-30 16:01:01

标签: reactjs mongodb express mongoose

尝试将已保存的游戏与保存该游戏的用户相关联时,我收到错误消息。错误显示“无法读取未定义的属性推送”

可以在控制台中读取用户和游戏。我认为这可能与用户初始创建期间的用户模型有关,但是我不确定。我确实注意到,如果我尝试console.log(user.favGames),它将返回未定义的状态。

我已经尝试了所有可以想到的事情,已经将控制器重写了大约10次,但无济于事。

用户模型

const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const SALT_ROUNDS = 6

const Schema = mongoose.Schema

const userSchema = new Schema(
  {
    username: { type: String, unique: true },
    email: { type: String, unique: true, unique: true },
    password: { type: String, required: true },
    avatar: { type: String },
    favGames: { type: Schema.Types.ObjectId, ref: 'Game', default: null },
    comments: { type: Schema.Types.ObjectId, ref: 'Comment', default: null }
  },
  {
    timestamps: true
  }
)

userSchema.set('toJSON', {
  transform: function(doc, ret) {
    delete ret.password
    return ret
  }
})

userSchema.pre('save', function(next) {
  const user = this
  if (!user.isModified('password')) return next()
  bcrypt.hash(user.password, SALT_ROUNDS, function(err, hash) {
    if (err) return next()
    user.password = hash
    next()
  })
})

userSchema.methods.comparePassword = function(tryPassword, cb) {
  bcrypt.compare(tryPassword, this.password, cb)
}

module.exports = mongoose.model('User', userSchema)

游戏模型

const mongoose = require('mongoose')

const Schema = mongoose.Schema

let gameSchema = new Schema({
  name: { type: String, required: true },
  boxArtUrl: { type: String, required: true },
  twitchID: { type: String, required: true },
  comments: { type: Schema.Types.ObjectId, ref: "Comment"}
})

module.exports = mongoose.model('Game', gameSchema)

游戏路由器

const express = require('express')
const router = express.Router()

const gamesCtrl = require('../../controllers/gameCtrl')

function isAuthed(req, res, next) {
  if (req.user) return next()
  return res.status(401).json({ msg: 'Unauthorized ' })
}

router.get('/')
router.post('/', isAuthed, gamesCtrl.addGame)

module.exports = router

游戏控制器

const User = require('../models/user')
const Game = require('../models/Game')

function addGame(req, res) {
  Game.create({
    name: req.body.name,
    twitchID: req.body.id,
    boxArtUrl: req.body.box_art_url
  })
    .then(game => {
      User.findById(req.user._id)
        .then(user => {
          console.log(game)
          console.log(user.favGames)
          // user.favGames.push(game)
          // user.save()
        })
        .catch(err =>
          console.log('error when updating user with new game', err)
        )
    })
    .catch(err => console.log('error saving game', err))
}

module.exports = {
  addGame
}

该错误在我的控制器中标记为user.favGames.push(game)。请注意,当用户创建个人资料时,没有与其个人资料相关联的游戏。我很确定我要调用模型的实际数据实例,而不是模型本身。预先感谢您的协助。

2 个答案:

答案 0 :(得分:0)

看起来好像要检查是否存在:

User.findById(req.user._id)
  .then(user => {
    if (!Array.isArray(user.favGames)) {
      user.favGames = [];
    }
    user.favGames.push(game);
    user.save();
  })

答案 1 :(得分:0)

您的favGames(以及注释)必须在这样的用户模型中定义为数组。

const userSchema = new Schema(
  {
    username: { type: String, unique: true },
    email: { type: String, unique: true, unique: true },
    password: { type: String, required: true },
    avatar: { type: String },
    favGames: [{ type: Schema.Types.ObjectId, ref: 'Game', default: null }],
    comments: [{ type: Schema.Types.ObjectId, ref: 'Comment', default: null }]
  },
  {
    timestamps: true
  }
)

也user.save()返回一个promise,所以您需要使用then阻止或等待。

所以addGame函数必须是这样的(我将代码转换为async / await)

async function addGame(req, res) {
  try {
    let game = await Game.create({
      name: req.body.name,
      twitchID: req.body.id,
      boxArtUrl: req.body.box_art_url
    });

    let user = await User.findById(req.user._id);

    if (user) {
      user.favGames.push(game);
      await user.save();
      res.status(200).send("game and user saved");
    } else {
      console.log("user not found");
      res.status(404).send("user not found");
    }
  } catch (err) {
    console.log("Err: ", err);
    res.status(500).send("Something went wrong");
  }
}