我正在尝试在这样的文档中对字段 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 解释为 double 而不是整数。我试过: parseInt(1)
但它也没有效果。我尝试使用 NumberInt(1)
但得到错误 NumberInt is not defined
。
所以我不能让它在我的代码中工作;但是,通过 mongo shell 的等效查询按预期工作:
db.query.update(
{"_id":ObjectId("58c3b98e458f0700045b1846")},
{"$bit":{"status":{"xor":NumberInt(1)}}}
)
我搜索了一下,发现 mongoose-int32 包中存在 NumberInt
,但它需要 mongoose。我不想将 Mongoose 添加为我的项目的依赖项,所以我正在寻找另一种解决方案。
最佳答案
问题来自文档中存储的 status
字段类型
这里是
{ "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()
})
}
})
这工作使用:
- Node v7.3.0
- npm 包 mongodb 2.2.24
- MongoDB 3.4.1
关于node.js - 没有 Mongoose ,不能从nodejs异或mongodb字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733778/