Как добавить имя пользователя и его идентификатор в поле пользователя в чате? - PullRequest
0 голосов
/ 03 августа 2020

Я создаю веб-приложение, в котором есть чаты, и пользователи могут присоединяться к чату. Как только пользователь присоединяется к чату, я хочу добавить идентификатор пользователя, а также его имя в поле пользователей в схеме чата. Пока я могу добавить их ID, но мне сложно добавить их имя. Ниже я прикрепил свою модель Chat mon goose, а также свой маршрут для добавления пользователя в чат. Также я прикрепил свою модель User mon goose. Любая помощь приветствуется. Спасибо!

Модель чата:

    const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ChatSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  creator: {
    type: Schema.Types.ObjectId,
    ref: 'user'
  },
  users: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: 'user'
      },
      name: {
        type: String,
        required: true
      }
    }
  ],
  code: {
    type: String,
    required: true
  },
  posts: [
    {
      text: {
        type: String,
        required: true
      },
      title: {
        type: String,
        required: true
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }

});

module.exports = Chat = mongoose.model('chat', ChatSchema);

маршрут для добавления пользователя в чат:

    // @route  Put api/chats
// @desc   Add a user to a chat
// @access Private
router.put('/', [auth,
  [
    check(
      'code',
      'Please include the code for the chat')
      .not()
      .isEmpty(),
    check(
      'password',
      'Please include the password for the chat'
    ).not()
      .isEmpty()
  ]
],
  async (req, res) => {

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    try {
      const chat = await Chat.findOne({ code: req.body.code });
      //const user = await User.findOne({ user: req.user.id });

      if (!chat) {
        return res.status(400).json({ msg: 'Invalid Credentials' });
      }

      // Check if the chat has already been joined by the user
      if (chat.users.filter(member => member.user.toString() === req.user.id).length > 0) {
        return res.status(400).json({ msg: 'Chat already joined' });
      }

      //console.log(chat.password);

      const isMatch = await bcrypt.compare(req.body.password, chat.password);

      if (!isMatch) {
        return res.status(400).json({ errors: [{ msg: 'Invalid Credentials' }] });
      }

      const newUser = {
        user: req.user.id,
        text: req.user.name
      }


      chat.users.unshift(newUser);

      await chat.save();

      res.json(chat.users);

    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });

Модель пользователя:

    const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model('user', UserSchema);

1 Ответ

0 голосов
/ 03 августа 2020

в этой части кажется, что вы назначаете имя пользователя свойству text, которое, я думаю, должно быть name, а не text.

const newUser = {
    user: req.user.id,
    text: req.user.name
  }

Код должен быть:

const newUser = {
    user: req.user.id,
    name: req.user.name //Property should be name
  }

Надеюсь, это сработает!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...