gpt4 book ai didi

node.js - 更新 MongoDB 中的字段

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:10 25 4
gpt4 key购买 nike

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

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);

最佳答案

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

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

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"})
})

})

关于node.js - 更新 MongoDB 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com