编译代码时出现这个错误
throw new mongoose.Error.OverwriteModelError(name);
^
OverwriteModelError: Cannot overwrite `users` model once compiled.
这是我的 Model/users.js 文件
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
//User Schema
const UserSchema = mongoose.Schema({
name: {
type:String
},
email: {
type:String,
required:true
},
username: {
type:String,
required:true
},
password: {
type:String,
required:true
}
});
const users = module.exports = mongoose.model('users',UserSchema);
module.exports.getUserById = function(id,callback)
{
User.findById(id,callback);
}
module.exports.getUserByUsername = function(username,callback){
const query = {username: username}
user.findOne(query,callback);
}
module.exports.addUser = function(newUser,callback){
bcrypt.genSalt(10,(err,salt)=>{
if(err)
{
throw err;
}
bcrypt.hash(newUser.password,salt,(err,hash)=>{
newUser.password=hash;
newUser.save(callback);
});
});
}
这是我的 route/users.js 文件
const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
var Log = require('log')
, log = new Log('info');
const User = require('../Model/users');
//const ap = express();
//Register router
router.post('/register',(req,res,next)=>{
log.info('entering register');
let newUser = new User({
name:req.body.name,
email:req.body.email,
username:req.body.username,
password:req.body.password
});
User.addUser(newUser,(err,user)=>{
log.info("inside add user");
if(err){
log.error('error while registaring ' + err);
res.json({success:false,msg:'failed to register user'});
}
else {
res.json({sucess:true,msg:'user registered succefully'});
}
})
});
router.get('/authenticate',(req,res,next)=>{
res.send("authenticated");
});
router.get('/profile',(req,res,next)=>{
res.send('profile');
});
module.exports=router;
护照.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../model/users');
const config = require('../config/database');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts,(jwt_payload,done)=>{
User.getUserById(jwt_payload._id,(err,user)=>{
if(err)
{
return done(err,false);
}
if(user){
return done(null,user);
}
else {
return done(null,false);
}
})
}));
}
我尝试了 [ Cannot overwrite model once compiled Mongoose 的建议 但我无法理解问题所在。
最佳答案
更新您的 require 语句,使其在路由和护照文件中保持一致:const User = require('../model/users');。大小写很重要!
您似乎没有使用正确的 Mongoose 术语。基于their documentation ,这应该大致如下实现。
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
//User Schema
const UserSchema = mongoose.Schema({
name: {
type:String
},
email: {
type:String,
required:true
},
username: {
type:String,
required:true
},
password: {
type:String,
required:true
}
});
UserSchema.statics.getUserById = function(id,callback)
{
return this.findById(id,callback);
};
UserSchema.statics.getUserByUsername = function(username,callback){
const query = {username: username}
return this.findOne(query,callback);
};
UserSchema.statics.addUser = function(newUser,callback){
bcrypt.genSalt(10,(err,salt)=>{
if(err)
{
throw err;
}
bcrypt.hash(newUser.password,salt,(err,hash)=>{
newUser.password=hash;
newUser.save(callback);
});
});
};
module.exports = users = mongoose.model('users',UserSchema);;
关于javascript - 编译 Node js 后无法覆盖 `users` 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150075/
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢