【问题标题】:mongoose getting `TypeError: user.save is not a function`猫鼬得到`TypeError:user.save不是函数`
【发布时间】:2020-05-06 22:44:50
【问题描述】:

当尝试使用猫鼬将用户数据发布到数据库时,问题是这样的:

为了让用户获得积分,我用条纹库向他收取“钱”,所以当我尝试将数据发布到数据库时,我得到了这个错误 - 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!');

【问题讨论】:

  • 你在哪里设置req.user
  • 在您登录后,护照不是为您做的吗? passport.initilizae 和 passport.session
  • 我以前没有用过太多,但我不认为它会自动为你做到这一点。查看文档here 似乎您需要设置自己的函数才能创建req.user 对象
  • 你能分享你的passport.js 文件在serializeUser 和deserializeUser 函数所在的位置吗,因为deserializeUser() 会设置你的req.user 对象

标签: node.js reactjs mongodb mongoose


【解决方案1】:

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

希望是有用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2019-01-18
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2019-10-05
    相关资源
    最近更新 更多