断言错误:1 == 0表示MongoDB deleteOne命令

时间:2017-02-13 13:50:41

标签: node.js mongodb express

我正在尝试为我正在处理的MongoDB / NodeJS / Express应用程序进行一些CRUD操作,并且我很难使用deleteOne命令,大概是因为我不知道我的查询,虽然我不知道为什么。

我从NodeJS driver documentation解除了mongoDB代码,我的代码块看起来像这样:

删除请求:

router.delete('/formula-list/:id', function(req, res){
  var db = req.db.collection('formulas');
  var id = req.params.id;
  var query = { "_id": id };
  db.deleteOne(query, function(err, r){
    assert.equal(null, err);
    assert.equal(1, r.deletedCount);
    db.close();
  });
  res.end();
});

当我运行它时,它返回错误AssertionError: 1 == 0,我认为这意味着该程序没有要删除的文档。

但是,如果我执行console.log(req.params.id),我会获得587f6ff4824d0a085c2b57bf,这是我数据库中文档的_id:

MongoDB document

console.log(db)返回以下内容:

的console.log(分贝):

{ s:
 { pkFactory:
  { [Function: ObjectID]
    index: 858167,
    createPk: [Function: createPk],
    createFromTime: [Function: createFromTime],
    createFromHexString: [Function: createFromHexString],
    isValid: [Function: isValid],
    ObjectID: [Circular],
    ObjectId: [Circular] },
 db:
  EventEmitter {
    domain: null,
    _events: {},
    _eventsCount: 0,
    _maxListeners: undefined,
    s: [Object],
    serverConfig: [Getter],
    bufferMaxEntries: [Getter],
    databaseName: [Getter] },
 topology:
  EventEmitter {
    domain: null,
    _events: [Object],
    _eventsCount: 7,
    _maxListeners: undefined,
    clientInfo: [Object],
    s: [Object] },
 dbName: 'formulas',
 options: { promiseLibrary: [Function: Promise], readConcern: undefined },
 namespace: 'formulas.formulas',
 readPreference:
  { _type: 'ReadPreference',
    mode: 'primary',
    tags: undefined,
    options: undefined },
 slaveOk: true,
 serializeFunctions: undefined,
 raw: undefined,
 promoteLongs: undefined,
 promoteValues: undefined,
 promoteBuffers: undefined,
 internalHint: null,
 collectionHint: null,
 name: 'formulas',
 promiseLibrary: [Function: Promise],
 readConcern: undefined } }

我认为这意味着Mongo集合本身也被识别,因为它没有返回undefined

对于我出错的任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

原生mongodb库需要_idObjectId

最终结果看起来更像是这样:

var mongo = require('mongodb');

// Other code lines

router.delete('/formula-list/:id', function(req, res){
  var db = req.db.collection('formulas');
  var query = { "_id": new mongo.ObjectId(req.params.id) };
  db.deleteOne(query, function(err, r){
    assert.equal(null, err);
    assert.equal(1, r.deletedCount);
    db.close();
  });
  res.end();
});