不能从没有mongoose的nodejs中异或mongodb字段

我试图在这样一个文件中异或的字段status

 { "_id" : ObjectId("58c51e1aedb6e4000410ddbf"), "query" : "developer", "user_id" : "1413322622039651", "status" : 1, "links" : [ "840673302343483394", "840672745222483968", "840672580717686785", "840672427550089216", "840582170548850688", "840581988918669312" ], "links_size" : 6, "created" : ISODate("2017-03-12T10:08:26.369Z") } 

我正在使用这个代码:

 var args = {'_id': new ObjectID(queryId)}; var bit = {$bit: {'status': {xor: 1}}}; db.collection('query').update(args, bit, function(err, result) {}); 

该查询不会产生错误,但字段status不会更改。 我认为问题在于它将1解释为一个不是整数的整数。 我试过: parseInt(1)但它也没有效果。 我试图使用NumberInt(1)但得到错误NumberInt is not defined

所以我不能让它在我的代码中工作; 但是,通过mongo shell的等效查询按预期工作:

 db.query.update( {"_id":ObjectId("58c3b98e458f0700045b1846")}, {"$bit":{"status":{"xor":NumberInt(1)}}} ) 

我GOOGLE了,发现NumberInt存在于mongoose-int32包中,但它需要mongoose。 我不想添加mongoose作为我的项目的依赖项,所以我正在寻找另一种解决scheme。

问题来自存储在文档中的status字段types

这里是

{ "status" : 1, ... }

但你应该有这个:

{ "status" : NumberLong(1), ... }

首先,使用此代码将所有状态字段转换为NumberLong(直接在shell中运行)

 db.query.find().forEach( function(obj) { obj.status = new NumberLong(obj.status); db.query.save(obj); }); 

那么就像这样更新你以前的代码:

 const MongoClient = require('mongodb').MongoClient const ObjectId = require('mongodb').ObjectId const Long = require('mongodb').Long MongoClient.connect('mongodb://localhost:27017/database', function (err, db) { if (err != null) { console.log(err) } else { let args = {'_id': new ObjectId('58c64231b13b6239d9e496da')} let bit = {$bit: {'status': {xor: Long.fromInt(1)}}} db.collection('query').update(args, bit, function (err, result) { if (err != null) { console.error(err) } db.close() }) } }) 

这工作使用:

  • 节点v 7.3.0
  • npm包mongodb 2.2.24
  • MongoDB 3.4.1