findOneAndUpdate不是函数 [英] findOneAndUpdate is not a function
本文介绍了findOneAndUpdate不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我整个上午都在使用Google搜索,并尝试了各种修复程序,但我无法弄清楚.
I've spent all morning googling this, and trying various fixes but I cannot figure it out.
当我尝试运行此错误时,我不断收到错误"TypeError:req.user.findOneAndUpdate不是函数":
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);
});
我尝试将req.user明确转换为User模型(例如var NewUser = new User(req.body),尝试简化查询等,但似乎无济于事.
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.
带有模型声明
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);}
});
用户模型架构
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;
和模型
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...
做:
User.findOneAndUpdate...
这篇关于findOneAndUpdate不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文