MongoDb deleteOne没有返回writeConcern?

时间:2016-09-23 15:45:56

标签: javascript mongodb database

我有一种基于id匹配删除MongoDb中特定文档的方法。代码如下。

deletePoll: function(db, user_id, callback) {
        db.collection('polls').deleteOne({
                _id: user_id
            },
            function(err, result) {
                if (err) {
                    console.log(err);
                }
                if(result){
                    console.log(result);
                }
            });
    }

现在,上面的代码只返回传递的if(result)上的大量对象。它记录的结果对象如下所示。

{ result: { ok: 1, n: 0 },
  connection: 
   EventEmitter {
     domain: null,
     _events: 
      { error: [Object],
        close: [Object],
        timeout: [Object],
        parseError: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     options: 
      { host: 'localhost',
        port: 27017,
        size: 5,
        connectionTimeout: 30000,
        socketTimeout: 30000,
        keepAlive: true,
        keepAliveInitialDelay: 0,
        noDelay: true,
        ssl: false,
        checkServerIdentity: true,
        ca: null,
        cert: null,
        key: null,
        passPhrase: null,
        rejectUnauthorized: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        reconnect: true,
        reconnectInterval: 1000,
        reconnectTries: 30,
        domainsEnabled: false,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        emitError: true,
        socketOptions: {},
        clientInfo: [Object],
        readPreference: [Object],
        promiseLibrary: [Function: Promise],
        bson: {} },
     id: 0,
     logger: { className: 'Connection' },
     bson: {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 30000,
     socketTimeout: 30000,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions: 
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     flushing: false,
     queue: [],
     connection: 
      Socket {
        _connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 8218,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleTimeout: 30000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 143353,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     workItem: null,
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null },
  message: 
   { parsed: true,
     index: 56,
     raw: <Buffer 38 00 00 00 36 00 00 00 23 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 14 00 00 00 10 6f 6b 00 01 00 00 00 10 6e ... >,
     data: <Buffer 38 00 00 00 36 00 00 00 23 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 14 00 00 00 10 6f 6b 00 01 00 00 00 10 6e ... >,
     bson: {},
     opts: 
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     length: 56,
     requestId: 54,
     responseTo: 35,
     responseFlags: 8,
     cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
     startingFrom: 0,
     numberReturned: 1,
     documents: [ [Object] ],
     cursorNotFound: false,
     queryFailure: false,
     shardConfigStale: false,
     awaitCapable: true,
     promoteLongs: true,
     promoteValues: true,
     promoteBuffers: false,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c' },
  deletedCount: 0 }

当我手动检查mongo控制台时,文档不会被删除。我在这做错了什么?为什么文档没有被删除?为什么writeConcern对象没有返回?为什么我会返回这个大型物体呢?

1 个答案:

答案 0 :(得分:0)

好的我认为你的问题可能是user_id。你传给那个参数的是什么?它是一个字符串?如果是这样,您可能需要将{ _id: new ObjectId(user_id) }作为deleteOne函数中的第一个参数。如果你查看输出的底部,它会显示deletedCount: 0。它可能尝试将字符串user_id与某个文档的_id匹配,该文档的类型为ObjectID。因此,既然您要将字符串与ObjectId进行比较,那么您似乎永远不会有匹配。 Documentation for ObjectId。我很确定这是问题所在。我之前遇到过类似的问题。如果这不能解决问题,您可以尝试以下建议。

此外,check this out看起来你应该传递过滤器对象,一个选项对象,然后是你的回调。看来你错过了选项对象。您可以尝试在回调之前传递null{}作为第二个参数。

虽然基于documentation for db,但您的问题似乎可能是时间问题。如果您将其置于严格模式,db.collection('colName')也会要求回拨。所以你可以尝试以下方法:

deletePoll: function(db, user_id, callback) {
        db.collection('polls', { strict: true }, function (err, col) {
            if (err) {
              // handle error
            } else {
              deleteUser(col);
            }
        });    
    }

function deleteUser(col) {
    col.deleteOne({
        _id: user_id
    },
    function(err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log(result);
        }
    });
}