更新MondoDB中的字段

时间:2019-05-31 08:47:35

标签: node.js mongodb

我正在编写多用户在线词典。我想建立一个领导委员会,例如用户添加单词后,“得分”属性就会增加。我对如何执行有一个粗略的想法,并尝试了一种解决方案,但是它不起作用。你能指导我吗?

Word API路由

const express = require('express');
const router = express.Router();
const Word = require('../../models/Word');
const User = require('../../models/User');

const validateWordInput = require('../../validation/word');
const passport = require('passport');

// @route  POST api/words
// @desc   Add words to profile
// @access Private
router.post(
  '/',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Word.find({}).then(word => {
      if (
        word.filter(
          wrd =>
            wrd.ugrWordCyr.toString().toLowerCase() ===
            req.body.ugrWordCyr.toLowerCase()
        ).length !== 0
      ) {
        return res
          .status(404)
          .json({ wordalreadyexists: 'Word already exists' });
      } else {
        const newWord = new Word({
          user: req.user.id,
          ugrWordCyr: req.body.ugrWordCyr,
          rusTranslation: req.body.rusTranslation,
          example: req.body.example,
          exampleTranslation: req.body.exampleTranslation,
          origin: req.body.origin,
          sphere: req.body.sphere,
          lexis: req.body.lexis,
          grammar: req.body.grammar,
          partOfSpeech: req.body.partOfSpeech,
          style: req.body.style
        });

        newWord.save().then(word => res.json(word));
        User.update(
          { _id: '5cf0cb78b3105d1ba8e30331' },
          { $inc: { score: 1 } }
        );
      }
    });
  }
);

用户模型

这是得分属性所在的位置

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

// Create schema
const userSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  score: {
    type: Number,
    default: 0
  },
  avatar: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

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

1 个答案:

答案 0 :(得分:2)

成功保存单词后,我们应该更新用户数

要更新相应用户的分数,您可以执行以下操作:

newWord.save().then((word) => {

    //now update user model
    User.findOne({ _id: req.user.id }) <-- or an id you would like
        .then((foundUser) => {
             foundUser.score = foundUser.score + 1

             foundUser.save()
                .then((savedUser) => {
                    res.json({ word, savedUser })
                })
                .catch((err) => {
                    return res.status(400).json({ error: "could not add score"})
                })
        })
        .catch((err) => {
           return res.status(400).json({ error: "could not find user"})
        })

})