我有以下代码在 mongodb findAndUpdateOne 更新查询中有语法错误。
router.post('/buylicense', isLoggedIn, function(req, res) {
if (!req.body.cid) {
return res.send('failed');
}
Company.findOne({
ownedBy: req.user.local.username,
_id: req.body.cid
}, function(err, result) {
if (err) {
return res.send('failed');
}
if (result.license) {
return res.send('valid');
} else {
Company.findOneAndUpdate({
ownedBy: req.user.local.username,
_id: req.body.cid
}, {
license: true,
licenseExpireDate: {
$add: ["$date", 3 * 24 * 60 * 60000] // bad code, a problem for another day
}
}, function(err) {
if (err) {
console.log(err);
return res.end('failed'); // Code should stop here.
}
console.log('got here');
return res.send('success');
});
}
});
console.log('How did I get here?');
res.send('failed');
});
我的问题是为什么代码到达代码的最后部分:
console.log('How did I get here?');
res.send('failed');
如果我使用 return res.end 以外的任何东西,代码会到达结尾并使我的应用程序崩溃。简单地执行 res.end 是行不通的,return res.send 也行不通。 return 或至少 res.end 是否足以真正阻止代码到达结尾?
如果我没有以正确的方式停止错误,就会显示错误,可能不相关,但这里是:
How did I get here?
{ CastError: Cast to date failed for value "[object Object]" at path "licenseExpireDate"
at MongooseError.CastError (/media/node_modules/mongoose/lib/error/cast.js:19:11)
at SchemaDate.cast (/media/node_modules/mongoose/lib/schema/date.js:242:9)
at SchemaDate.castForQuery (/media/node_modules/mongoose/lib/schema/date.js:276:17)
at Query._castUpdateVal (/media/node_modules/mongoose/lib/query.js:2477:17)
at Query._walkUpdatePath (/media/node_modules/mongoose/lib/query.js:2372:25)
at Query._castUpdate (/media/node_modules/mongoose/lib/query.js:2296:23)
at castDoc (/media/node_modules/mongoose/lib/query.js:2500:18)
at Query._findAndModify (/media/node_modules/mongoose/lib/query.js:1755:17)
at Query._findOneAndUpdate (/media/node_modules/mongoose/lib/query.js:1622:8)
at /media/node_modules/kareem/index.js:156:8
at args (/media/node_modules/kareem/index.js:71:20)
at Query.<anonymous> (/media/node_modules/mongoose/lib/schema.js:728:7)
at next (/media/node_modules/kareem/index.js:82:14)
at Kareem.execPre (/media/node_modules/kareem/index.js:99:3)
at Kareem.wrap (/media/node_modules/kareem/index.js:146:8)
at Query._findOneAndUpdate (/media/node_modules/kareem/index.js:188:11)
message: 'Cast to date failed for value "[object Object]" at path "licenseExpireDate"',
name: 'CastError',
kind: 'date',
value: { '$add': [ '$date', 259200000 ] },
path: 'licenseExpireDate',
reason: undefined }
got here
_http_outgoing.js:346
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
at ServerResponse.header (/media/node_modules/express/lib/response.js:718:10)
at ServerResponse.send (/media/node_modules/express/lib/response.js:163:12)
at /media/sf_vShared/xyz/app/modalRoutes.js:461:28
at /media/node_modules/kareem/index.js:160:11
at Query._findAndModify (/media/node_modules/mongoose/lib/query.js:1767:14)
at Query._findOneAndUpdate (/media/node_modules/mongoose/lib/query.js:1622:8)
at /media/node_modules/kareem/index.js:156:8
at args (/media/node_modules/kareem/index.js:71:20)
at Query.<anonymous> (/media/node_modules/mongoose/lib/schema.js:728:7)
at next (/media/node_modules/kareem/index.js:82:14)
at Kareem.execPre (/media/node_modules/kareem/index.js:99:3)
at Kareem.wrap (/media/node_modules/kareem/index.js:146:8)
at Query._findOneAndUpdate (/media/node_modules/kareem/index.js:188:11)
at Query.findOneAndUpdate (/media/node_modules/mongoose/lib/query.js:1611:15)
at Function.Model.findOneAndUpdate (/media/node_modules/mongoose/lib/model.js:1491:13)
[nodemon] app crashed - waiting for file changes before starting...
最佳答案
首先让我们看看三个ExpressJS函数有什么区别
res.end: 来自 NodeJS 核心。在 Express JS 中如果你需要快速结束请求并且不需要发送任何数据那么你可以使用这个函数
res.send:发送数据并结束请求
res.json 以JSON格式发送数据并结束请求。
My question is why is the code reaching the last part of the code:?
我希望您知道 JavaScript 是异步语言。使用 Mongoose 对 MongoDB 的所有数据库调用都是异步的。所以Compnay.findOne是一个异步函数调用,它停留在事件循环中,直到数据库读取操作未完成。作为 JS 的异步行为,JS 主线程执行不会等待 DB 函数结果返回(无阻塞)并到达最后一行,并且您的请求以调用 res.end("failed") 结束。但是当数据库读取操作完成返回数据时,您再次调用 res.send你以 Error: Can't set headers after they are sent. 结尾
希望这有帮助:)
关于Node.js res.send VS res.end VS 返回res.end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38220467/
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
所以我开始关注ruby,很多东西看起来不错,但我对隐式return语句很反感。我理解默认情况下让所有内容返回self或nil但不是语句的最后一个值。对我来说,它看起来非常脆弱(尤其是)如果你正在使用一个不打算返回某些东西的方法(尤其是一个改变状态/破坏性方法的函数!),其他人可能最终依赖于一个返回对方法的目的并不重要,并且有很大的改变机会。隐式返回有什么意义?有没有办法让事情变得更简单?总是有返回以防止隐含返回被认为是好的做法吗?我是不是太担心这个了?附言当人们想要从方法中返回特定的东西时,他们是否经常使用隐式返回,这不是让你组中的其他人更容易破坏彼此的代码吗?当然,记录一切并给出
为什么以下不同?Time.now.end_of_day==Time.now.end_of_day-0.days#falseTime.now.end_of_day.to_s==Time.now.end_of_day-0.days.to_s#true 最佳答案 因为纳秒数不同:ruby-1.9.2-p180:014>(Time.now.end_of_day-0.days).nsec=>999999000ruby-1.9.2-p180:015>Time.now.end_of_day.nsec=>999999998
在Ruby1.9.3(可能还有更早的版本,不确定)中,我试图弄清楚为什么Ruby的String#split方法会给我某些结果。我得到的结果似乎与我的预期相反。这是一个例子:"abcabc".split("b")#=>["a","ca","c"]"abcabc".split("a")#=>["","bc","bc"]"abcabc".split("c")#=>["ab","ab"]在这里,第一个示例返回的正是我所期望的。但在第二个示例中,我很困惑为什么#split返回零长度字符串作为返回数组的第一个值。这是什么原因呢?这是我所期望的:"abcabc".split("a")#=>["bc"
我一直在研究RubyKoans,我发现about_open_classes.rbkoan很有趣。特别是他们修改Integer#even?方法的最后一个测试。我想尝试一下这个概念,所以我打开了Irb并尝试运行Integer.respond_to?(:even?),但令我惊讶的是我得到了错误。然后我尝试了Fixnum.respond_to?(:even?)并得到了错误。我还尝试了Integer.respond_to?(:respond_to?)并得到了true,当我执行2.even?时,我也得到了true。我不知道发生了什么。谁能告诉我缺少什么? 最佳答案
无论时间在哪个时区表示,时区差异是否总是被忽略?直觉上,对于那些使用UTC+2的人来说,从EPOCH开始经过的秒数应该更高。然而,事实并非如此。 最佳答案 Epoch基于utc时区https://en.wikipedia.org/wiki/Unix_time它与您当前所在的时区无关。 关于ruby-Time.to_i是否总是以UTC返回自EPOCH以来的秒数?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.
我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id
我有一个非常简单的Controller来管理我的Rails应用程序中的静态页面:classPagesController我怎样才能让View模板返回它自己的名字,这样我就可以做这样的事情:#pricing.html.erb#-->"Pricing"感谢您的帮助。 最佳答案 4.3RoutingParametersTheparamshashwillalwayscontainthe:controllerand:actionkeys,butyoushouldusethemethodscontroller_nameandaction_nam
假设我们有一个字符串str。如果str仅包含一个字符,例如str="1",则str[-1..1]返回1.但是如果str的size(length)比一个长,比如str="anythingelse",然后str[-1..1]返回""(空字符串)。为什么Ruby会这样解释字符串切片? 最佳答案 这种行为正是字符范围的工作方式。范围开始是-1,这是字符串中的最后一个字符。范围结束为1,即从开始算起的第二个位置。所以对于单字符字符串,这相当于0..1,也就是那个单个字符。对于双字符字符串,这是1..1,即第二个字符。对于三个字符的字符串,这是