首页 > 解决方案 > 猫鼬得到`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!');

标签: node.jsreactjsmongodbmongoose

解决方案


.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){
 // ...
 }
})()

希望有用。


推荐阅读