解析为JSON的字符串导致AssertionError:{[MongoError:无法规范化查询:BadValue $或/ $和/ $条目也不需要是完整对象]

时间:2016-01-08 18:59:44

标签: json mongodb

我正在尝试根据getBooksFromDB()函数的参数创建json对象,以适应多种条件的以下语法: -

var cursor = db.collection('books').find({ $or:[{condition1},{condition2},...] });

数据库:( Mongodb)

{ _id: ObjectID { _bsontype: 'ObjectID', id: 'VI\u001b\u001aQ\nÀ\r±[' },
  title: 'TestBook',
  author: 'Amresh Venugopal',
  tags: [ 'junk', 'useless book' ] }
{ _id: ObjectID { _bsontype: 'ObjectID', id: 'V\u0002\u0000a\u001dsÔ\r¡Í' },
  title: 'BlackBook I',
  author: 'Hermaeus Mora',
  tags: [ 'skyrim', 'magic', 'armour' ] }
{ _id: ObjectID { _bsontype: 'ObjectID', id: 'V\u0002\u000fÛ¢Så\rK¢æ' },
  title: 'BlackBook II',
  author: 'Hermaeus Mora',
  tags: [ 'skyrim', 'magic', 'shouts' ] }

和代码:

var getBooksFromDB = function(db, title, author, tags, callback){
    var query = "";

    if(typeof title !== undefined) {
        query += "{'title': '" + title + "'},";
    }

    if(typeof author !== undefined) {
        query += "{'author': '" + author + "'},";
    }

    query = JSON.parse(JSON.stringify(query));  
    var cursor = db.collection('books').find({
            $or:[query]
        });

    cursor.each(function(err, doc){
        assert.equal(err, null);
        if(doc != null) {
            console.dir(doc);
        } else {
            callback();
        }
    });

}

MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    getBooksFromDB(db, "TestBook", "Amresh Venugopal", function() {
        db.close();
    });
});

控制台上的var query如下所示:

{'title': 'TestBook'},{'author': 'Amresh Venugopal'}

错误:

AssertionError: { [MongoError: Can't canonicalize query: BadValue
$or/$and/$nor entries need to be full objects]
name: 'MongoError', message == null

0 个答案:

没有答案