I've spent all morning googling this, and trying various fixes but I cannot figure it out.
I keep getting the error "TypeError: req.user.findOneAndUpdate is not a function" when I try to run this:
req.user.findOneAndUpdate({_id: req.user._id}, { $addToSet: { flashcards : { $each: cards }}}, {upsert : true}, function(err, doc) {
if(err) return console.log(err);
res.send(doc);
});
I've tried explicitly turning req.user into a User model (eg var NewUser = new User(req.body), tried simplifying the query etc but nothing seems to work.
Edit: With model declaration
const User = require('../models/user');
var NewUser = new User(req.user);
NewUser.findOneAndUpdate({_id: req.user._id}, { $addToSet: { flashcards : { $each: cards }}}, {upsert : true}, function(err, doc) {
if(err) { return console.log(err); }
else { return res.send(doc);}
});
User model schema
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
FlashcardSchema = require('./flashcardSchema'),
bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema({
username: {
type: String,
required: false
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String
},
created_on: {
type: Date,
default: Date.now
},
points: Number,
flashcards: [FlashcardSchema],
courses: [{type: Schema.Types.ObjectId, ref: 'Course'}]
});
UserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = UserSchema;
And the model
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
UserSchema = require('../schemas/userSchema');
module.exports = mongoose.model('User', UserSchema);
The solution is to run functions on a model, not on a instance of it. So instead of:
var NewUser = new User(req.user);
NewUser.findOneAndUpdate...
Do:
User.findOneAndUpdate...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With