小编Car*_*sel的帖子

使用JavaScript检测Android后退按钮的使用

我的网站有面包屑,突出显示用户已达到的流程中的哪个阶段.面包屑依赖于浏览器历史记录来告诉在使用浏览器后退按钮时应该突出显示哪个阶段,但是在使用硬件后退按钮的Android设备上,这似乎被绕过并且突出显示的痕迹不会改变.

我的网站没有使用PhoneGap或任何类似的东西,因为它通常不是移动网站,因此可以捕获Android后退按钮的使用,以便我可以添加一个事件来设置基于历史记录日志按钮时的痕迹突出显示使用,只使用JavaScript或jQuery?

javascript android

11
推荐指数
1
解决办法
6864
查看次数

传入的参数必须是24个十六进制字符的字符串 - 我认为是

我有一种方法可以根据ObjectID在我的数据库中查找文档:

      console.log('id: ' + id + ' type: ' + typeof id);
      collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
        if (error) {
          callback(error);
        } else {
           callback(null, doc);
        }
      });
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;      
          ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41
Run Code Online (Sandbox Code Playgroud)

这是指collection.findOne()上面的一行.

我在调用之前的控制台日志输出id为24个十六进制字符的字符串:

id: "55153a8014829a865bbf700d" type: string
Run Code Online (Sandbox Code Playgroud)

在此之前,我将id从一个对象转换为一个字符串,JSON.stringify()但它似乎成功运行,如我的console.log所示.

db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")})在Robomongo中运行会带来预期的结果.

mongodb node.js monk

7
推荐指数
2
解决办法
3万
查看次数

批量删除汇总的文档

我试图对mongoose聚合查询的结果使用批量删除.

var bulk = Collection.collection.initializeUnorderedBulkOp();
var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec();

cursor.each(function(error, doc){
  if(doc){
    console.log(doc);
    bulk.find({_id : doc._id}).removeOne();
  }
});

if(bulk.length > 0) {
  bulk.execute(function(error){
    if(error){
      console.error(error);
      callback(error);
    }else{
      console.log(bulk.length + " documents deleted");
      callback(null);
    }
  });
} else {
  console.log("no documents to delete");
  callback(null);
}
Run Code Online (Sandbox Code Playgroud)

这导致在每个循环中聚合结果之前打印"无文档删除".通常我希望有一个数据库操作的回调函数.我试过在exec的params中添加一个回调函数,但函数永远不会被命中:

var cursor = Collection.aggregate(query).cursor({batchSize: 1000}).exec(function(error, result){
  console.log(error);
  console.log(result);
  callback();
});
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongodb-query aggregation-framework

7
推荐指数
1
解决办法
438
查看次数

无法打开 .rdb 进行保存:权限被拒绝 - 成功运行一段时间后启动

我有一个节点 Web 服务在 aws ubuntu 服务器上成功运行了一个多月,请求使用 redis 缓存。

昨天我开始从我的一些路线中收到以下错误:

MICONF Redis 配置为保存 RDB 快照,但目前无法在磁盘上持久化。可以修改数据集的命令被禁用。有关错误的详细信息,请检查 Redis 日志。

我能够通过使用来阻止发生的错误:

config set stop-writes-on-bgsave-error no
Run Code Online (Sandbox Code Playgroud)

正如这个问题的答案中所建议的那样,但它实际上并没有解决根本问题。

为了找到潜在的问题,我检查了日志,发现以下情况已经开始发生:

[1105] 09 Aug 13:17:14.800 - 0 clients connected (0 slaves), 797680 bytes in use
[1105] 09 Aug 13:17:15.101 * 1 changes in 900 seconds. Saving...
[1105] 09 Aug 13:17:15.101 * Background saving started by pid 28090
[28090] 09 Aug 13:17:15.101 # Failed opening .rdb for saving: Permission denied
[1105] 09 Aug 13:17:15.201 # Background saving …
Run Code Online (Sandbox Code Playgroud)

redis

6
推荐指数
0
解决办法
1729
查看次数

中断从循环调用的方法

我正在重构一个非常大的方法,里面有很多重复.

在该方法中有许多while循环,包括:

    if ( count > maxResults){
        // Send error response
        sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
        break;
Run Code Online (Sandbox Code Playgroud)

我想把它作为一种方法提取,因为它在当前的这个方法中发生了3次,但是当我这样做时,我在中断时得到一个错误,因为它不再在循环中.问题是仍然需要打破while循环,但仅在达到最大结果数时.

有什么建议?

java methods break while-loop

5
推荐指数
1
解决办法
359
查看次数

使用快速验证器进行单元测试验证

如何对使用express-validator完成的验证进行单元测试?

我尝试创建一个虚拟请求对象,但收到错误消息:TypeError: Object #<Object> has no method 'checkBody'。我能够手动测试验证在应用程序中是否有效。

这是我尝试过的:

describe('couponModel', function () {
    it('returns errors when necessary fields are empty', function(done){
        var testBody = {
            merchant : '',
            startDate : '',
            endDate : ''
        };
        var request = {
            body : testBody
        };
        var errors = Model.validateCouponForm(request);
        errors.should.not.be.empty;
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

我的理解是,checkBody当我app.use(expressValidator())在快速应用程序中使用该方法时,该方法已添加到请求对象中,但是由于我仅测试该验证在此单元测试中有效,因此我没有可用的快速应用程序实例,并且该验证我正在测试的方法无论如何都不会直接从它调用,因为它只是通过发布路由来调用,我不想调用单元测试,因为它涉及数据库操作。

validation unit-testing node.js express

5
推荐指数
2
解决办法
1961
查看次数

geoNear例外:“ near”字段必须为point

我已经在mongo shell中成功运行了以下查询:

db.runCommand({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
})
Run Code Online (Sandbox Code Playgroud)

我正在尝试将其转换为对node服务的猫鼬查询, 如docs所示

Store.geoNear(
    { type : "Point", coordinates : [-3.978, 50.777]}, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});
Run Code Online (Sandbox Code Playgroud)

这将返回以下错误:

MongoError: exception: 'near' field must be point
Run Code Online (Sandbox Code Playgroud)

我的Store架构是这样定义的:

var storeSchema = new Schema({
    // irrelevant fields...
    locations : [
        { …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb

5
推荐指数
1
解决办法
2800
查看次数

使用pauseOnConnect通过https传递连接

我正在使用pauseOnConnecton选项,net.createServer()以允许我将连接传递给使用群集创建的工作程序。

server = net.createServer({ pauseOnConnect : true }, function(connection){
    console.log('passing connection to worker...');
    // received a connection and need to pass it to the appropriate worker
    var workerIndex = getWorkerIndex(connection.remoteAddress, numberOfProcesses);
    var worker = workers[workerIndex];
    worker.send("sticky-session:connection", connection);
}).listen(portNumber, function(){
    logger.info("Server started on port " + portNumber);
});
Run Code Online (Sandbox Code Playgroud)

我是否pauseOnConnect可以通过使用https模块或将net服务器转换为使用https 来与https 一起使用?

node.js

5
推荐指数
1
解决办法
513
查看次数

Mongodb在组内聚合排序和限制

我有以下架构的待售物品集合:

var itemSchema = new Schema({
    "category" : { type : Schema.Types.ObjectId, ref : 'Category' },
    "merchant" : { type : Schema.Types.ObjectId, ref : 'Merchant' },
    "rating" : Number
})
Run Code Online (Sandbox Code Playgroud)

我继承了一个聚合查询,该查询返回与按类别划分的类别的项目,按商家分组,组按组中的最大评级排序:

Item.aggregate([
      { "$match" : { category : categoryId, merchant : { $ne : null }}},
      { "$group" : { _id : "$merchant", 
                    rating : { $max : "$rating" }, 
                    items : { $push : "$$ROOT" }}},
      { "$sort" : { rating : -1 }}
    ], { allowDiskUse : true …
Run Code Online (Sandbox Code Playgroud)

mongodb mongodb-query aggregation-framework

4
推荐指数
1
解决办法
4842
查看次数

使用无序批量更新时“未定义不是函数”

我正在使用批量增补一次将多个文档更新/添加到我的数据库中:

var bulk = collection.initializeUnorderedBulkOp();
docs.forEach(function(doc, index, array){
  bulk.find({'docId' : doc.docId}).upsert().updateOne(doc);
});
bulk.execute();
Run Code Online (Sandbox Code Playgroud)

bulk.execute此返回以下错误:

/myPath/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:771
  catch(err) { process.nextTick(function() { throw err}); }
                                                   ^
TypeError: undefined is not a function
    at /myPath/node_modules/mongodb/lib/bulk/unordered.js:470:5
Run Code Online (Sandbox Code Playgroud)

我看了mongodb模块中的代码,这里的回调似乎失败了:

// Execute batches
return executeBatches(this, function(err, result) {
  callback(err, result);
});
Run Code Online (Sandbox Code Playgroud)

数据已完全按预期写入数据库,但仍会引发此错误,并且我无法弄清楚导致该错误的方法。

我已经通过使用琐碎的对象以及使用批量插入而不是upsert排除了数据方面的问题,因为它们比较简单,但是结果是相同的。

mongodb node.js

3
推荐指数
1
解决办法
817
查看次数