我正在尝试创建一个将触发预验证中间件的“findOneAndUpdate”查询。
当请求正文中未提供时,需要这些中间件来验证给定坐标并创建“id”字段(是的,不是“_id”字段)。
正如您在下面看到的(请参阅代码中的注释),我很接近,但不明白为什么 mongo 抛出的错误是重复键多样性。
也许 promises 不是去这里的方式,尽管它们让我能够完成比链式 pre 中间件更多的事情。
这是我的 Express 路线:
/* POST /geolocs */
router.post('/', function(req, res, next) {
Geoloc.create(req.body, function(err, post) {
if (err) return next(err);
res.status(201).json(post);
});
});
这是我的架构:
var GeolocSchema = new mongoose.Schema({
id: {
type: String,
required: true,
unique: true
},
location: {
type: {
type: String,
default: 'Point',
required: true
},
coordinates: {
type: [Number],
required: true
}
},
count: Number
});
GeolocSchema.index({
location: '2dsphere'
});
预验证中间件:
// Before validation, check given coordinates for errors.
GeolocSchema.pre('validate', function(next) {
coord = this.location.coordinates
if (this.location.type && coord) {
if (Array.isArray(coord) && coord.length === 2) {
lat = coord[1];
lon = coord[0];
if ((-90 <= lat && lat <= 90) && (-180 <= lat && lat <= 180)) next();
}
}
var err = new Error('...'); // Long error text, irrelevant here
err.status = 400;
next(err);
});
// Then, if no 'id' is given, create it.
GeolocSchema.pre('validate', function(next) {
if (!this.id) {
strLat = this.location.coordinates[1].toFixed(3).replace('.', '_');
strLon = this.location.coordinates[0].toFixed(3).replace('.', '_');
this.id = strLat + '-' + strLon;
}
next();
});
我希望能够做的是在上面的下面添加以下内容:
// Here, using the validate or save hook doesn't change anything.
GeolocSchema.pre('validate', function(next) {
var prom = Geoloc.findOne({
'id': {
$eq: this.id
}
}).exec();
prom.then((err, geoloc) => { // Arrow function here to access 'this'
if (err) next(err);
// If no geoloc was found, go ahead and save.
if (!geoloc) next();
// Else, update to increment the count (THIS WORKS).
return Geoloc.update({'id': this.id}, {$inc: {count: 1}}).exec();
}).then((toto) => {
// This doesn't work, the error thrown by mongo is a duplicate key error (E11000).
if (toto) next(new Error('204'));
else next(new Error("Something that shouldn't happen, happened..."));
});
});
最佳答案
问题是 pre() 和 post() 中间件 save 和 validate 没有被执行通过 update()、findOneAnUpdate() 等。它在 docs 中提到还有一个 GitHub issue
但是,有 pre('findOneAndUpdate') 和 post('findOneAndUpdate') Hook 可用(不确定 update 的 Hook 是否可用> 作品)。
希望对你有帮助。
关于node.js - 在预验证中间件之后创建或更新字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41717602/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake