javascript - 排除字段保存在 Node mongodb native 中

标签 javascript node.js mongodb

我正在使用 node mongodb native driver 插入文档进入 mongodb(原文如此!)。我的对象看起来像这样:

var x = {
  field: 'value',
  _nonPersistentField: 'Do not save that'
};

我想实现的是,防止所有以下划线为前缀的字段不被保存。在上面的示例中,不应保存“_nonPersistentField”。

有没有办法(Object.defineProperty 除外)防止这些字段被保存在 Node mongodb native 中?

最佳答案

预解析器呢?不要使用来自 mongo 客户端的 save,而是使用:

function save( obj, callback ) {
    var tmp = {};
    Object.keys( obj ).forEach( function( key ) {
        if ( key.substr( 0, 1 ) !== '_' ) {
            tmp[ key ] = obj[ key ];
        }
    } );

    // Now that the object is filtered, use mongodb's client
    mongodb.save( tmp, callback );
}

使用这种方式,您甚至看不到对象的创建等等,而不是:

mongodb.save( obj, function( err, results ) {
} );

您正在使用:

save( obj, function( err, results ) {
} );

关于javascript - 排除字段保存在 Node mongodb native 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11133479/

相关文章:

MongoDB 自签名 SSL 连接 : SSL peer certificate validation failed

mongodb - Docker Compose 了解端口映射

javascript - 使用 CodeIgniter 通过 AJAX 提交表单

javascript - 诊断 Javascript 泄漏类型

node.js - 无法使用 Azure 函数找到模块 grpc_node.node

node.js - Semaphore CI ruby​​ 项目上的 Javascript (Jest) 测试

javascript - for循环每次在Livescript中分配相同的功能

javascript - ReactJs onClick 添加类名

javascript - Meteor 中的文件路径

mongodb - 查询嵌套组并插入 mongodb