node.js - 猫鼬得到`TypeError:user.save不是一个函数`
问题描述
当尝试使用猫鼬将用户数据发布到数据库时,问题是这样的:
为了让用户获得积分,我用条纹库向他收取“钱”,所以当我尝试将数据发布到数据库中时,我得到了这个错误-TypeError: req.user.save is not a function
代码如下: //用户模型
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserSchema = new Schema({
googleId: String,
credits: { type: Number, default: 0}
});
mongoose.model('users', UserSchema);
//Route code
const keys = require('../config/keys');
const stripe = require('stripe')(keys.stripeSecretKey);
const User = require('../models/User');
module.exports = app => {
app.post('/api/stripe', async (req, res) => {
const charge = await stripe.charges.create({
amount: 500,
currency: 'usd',
description: '$5 for 5 credits',
source: req.body.id
});
req.user.credits += 5;
const user = await req.user.save();
res.send(user);
});
};
//Index file
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const bodyParser = require('body-parser');
const passport = require('passport');
require('./models/User');
require('./services/passport');
mongoose.connect(keys.mongoURI);
const app = express();
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
require('./routes/authRoutes')(app);
require('./routes/billingRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT);
console.log('The server is running!');
解决方案
.save() 这是一个应该在 MongoDB 对象上使用的方法。
首先,您应该在 MongoDB 中找到您的用户,例如:
(async()=>{
try{
const user = await User.findById(userID)
// now user is an Object which has the .save() method
// now you can modify the name of the userm for example
user.name = "new name"
// after saving the changes wit .save() method
await user.save() // you're connecting with DB to communicate about introducing new data
// ...
}catch(err){
// ...
}
})()
希望有用。
推荐阅读
- sql - PostgreSQL 将数据聚合成单行
- amazon-web-services - AWS API Gateway - 无法使用外部 HTTPS 端点信任的 CA 签名客户端证书
- sql - 如果连接表有 2 列或更多列,则更新表的字段
- c# - 使用相同对象生成校验和时发生更改
- java - 消费者阅读 __consumer_offsets 传递不可读的消息
- assembly - 程序如何在堆栈中找到全局变量?
- java - Java - JFrame 不显示 ImageIcon
- python - 导入时未定义枚举对象 - Python 3 通过 Jupyter Notebook
- ios - Why my does blur view become transparent when I combine with UIImagview?
- html - Angular6/Typescript - Mapping of Objects in Arrays in Arrays