【问题标题】:Insert Array in existing Document在现有文档中插入数组
【发布时间】:2015-09-26 17:09:50
【问题描述】:

我有这样的文件:

_id: ObjectId("559c1d2ad8291bc9368b4568")
 tablename: "IWEO_IWBB"
 out_user: "pb"
 out_email: "email"
 out_date: "15.05.2015"

并想像这样添加数组:

"inventar": [
    {
        "ean": "2",
        "name": "name2",
        "runtime": "0",
        "art": "null",
        "marker": "null",
        "stammkost": "null",
        "accepted": "0"
    },
    {
        "ean": "1",
        "name": "name1",
        "runtime": "0",
        "art": "null",
        "marker": "null",
        "stammkost": "null",
        "accepted": "0"
    }
],

在我的旧 PHP-Server 中,我使用下面的代码插入它。 正确的命令是“更新”。在 node.js 中,它似乎是另一个命令。

foreach($jArray as $value){ 
    //$uuid = uniqid('', true);
    $tablename = $value['tablename'];
    $ean = $value["ean"];
    $runtime = $value["runtime"];
    $art = $value["art"];
    $marker = $value["marker"];
    $stammkost = $value["stammkost"];
    $new_data = array(
        //array (
        'ean' => $ean,
        'runtime' => $runtime,
        'art' => $art,
        'marker' => $marker,
        'stammkost' => $stammkost,
        'accepted' => '0'
        //)
    );
    try {
        $collection->update(array("tablename"=>$tablename),array('$push' => array("inventar" => $new_data)));
        echo json_encode($collection);
    }
    catch ( MongoConnectionException $e ) {
        echo '<p>Update failed</p>';
        exit();
    }           
}

在我的新 node.js 中,我使用以下代码:

tables.forEach(function(table) {
var tablename = table.tablename;
var name = table.name ;
var ean = table.ean;
var runtime= table.runtime;
var art = table.art;
var marker = table.marker;
var stammkost = table.stammkost;
console.log(tablename+" "+ean+" "+name+" "+runtime+" "+art+" "+marker+" "+stammkost);
    OutAccept.update(function (err, data) {
    if (err) console.log(err);
    else {
    console.log(data);
    }
    });
    response.end();
    //}
    });

});

控制台的输出是:

IWEO_IWBB_01062015 1 name1 11337 A null null
{ ok: 0, n: 0, nModified: 0 }
IWEO_IWBB_01062015 2 name2 A null null
{ ok: 0, n: 0, nModified: 0 }

为什么没有更新/插入?是不是命令不对?

【问题讨论】:

  • 那么您是否在遇到问题的 node.js 服务器上使用 PHP?
  • '$push'?这是一个包含字符$pu 等的字符串……它不是一个名为 push 的变量。
  • 抱歉,我想从 php 迁移到 node。在 php 中它的工作,在节点 Not yet
  • @MarcB 你没有阅读我的问题。 php 部分正在运行,不予讨论...
  • 我想我应该使用 findOneAndUpdate gist.github.com/aheckmann/3005513

标签: javascript node.js mongodb mongodb-query


【解决方案1】:

您的代码中存在一些问题。首先要注意的是,您现在在“异步”环境中运行,您需要改变对如何做一些事情的想法。

您之前的 PHP 代码是“阻塞的”,这意味着必须完成每一行代码才能继续执行下一行代码。这包括等待数据库服务器执行更新并返回响应。

您不能使用带有异步执行功能的基本控制循环。相反,一旦异步函数“update”实际返回了结果,您需要一些可以调用循环的下一次迭代(或至少发出单次迭代已完成的信号)的东西。

这里的第二点是“没有更新”,因为您没有告诉函数要更新什么或用什么来更新匹配的文档。

以下内容类似于您的原始 PHP 清单,但针对“异步”方法进行了调整,还使用了来自 async 库的 async.eachSeries 循环控制:

async.eachSeries(
    tables,
    function(table,callback) {
        var tablename  = table.tablename;
        delete table.tablename;   // just remove the key rather than re-construct
        OutAccept.update(
            { "tablename": tablename },
            { "$push": { "inventar": table } },
            function(err,numAffected) {
                console.log( numAfftected ); // tells you how many are updated or nothing
                callback(err)
            }
        );
    },
    function(err) {
       // comes here on completion of all array items
    }
);

.findOneAndUpdate() 命令改为返回已修改的文档,并且仅当您使用 { "new": true } 要求时才返回修改后的文档

async.eachSeries(
    tables,
    function(table,callback) {
        var tablename  = table.tablename;
        delete table.tablename;
        OutAccept.findOneAndUpdate(
            { "tablename": tablename },
            { "$push": { "inventar": table } },
            { "new": true },
            function(err,doc) {
                console.log( doc ); // shows the modified document
                callback(err)
            }
        );
    },
    function(err) {
       // comes here on completion of all array items
    }
);

如果你想一次添加多个数组元素,或者如果你在一个数组中直接有一个元素,那么使用$each 修饰符到$push

var inventor =  [
    {
        "ean": "2",
        "name": "name2",
        "runtime": "0",
        "art": "null",
        "marker": "null",
        "stammkost": "null",
        "accepted": "0"
    },
    {
        "ean": "1",
        "name": "name1",
        "runtime": "0",
        "art": "null",
        "marker": "null",
        "stammkost": "null",
        "accepted": "0"
    }
];


OutAccept.update(
    { "tablename": tablename },
    { "$push": { "inventar": { "$each": inventar } } },
    function(err,numAffected) {
       // work in here
    }
);

【讨论】:

  • 它想到了结构,我将打开一个新线程。如果您阅读stackoverflow.com/questions/31298624/…,那就太好了
  • 你的代码中有什么不被接受的?在我的代码中定义了模型模式,我仍然无法得到它
  • @Piet 只是复制您的代码,假设这是正确的模型。这里的操作都是按原样工作的。
  • 我对 mongoose 中的模型有理解问题。我创建了完整的模式并用值填充它? var moveSchema = new mongoose.Schema({ tablename: String , OutUser: String , OutEmail: String , OutDate: String , InUser: String , InEmail: String , InDate: String , accepted: String , inventar: Array }); 或者我为每个数据库操作创建一个新模式?我无法为同一个集合创建 2 个不同的模型/模式。我会得到`无法覆盖Movements模型一旦编译。`(运动是我的收藏)
  • doc.findOneAndUpdate( { "tablename": tblname }, { "$push": { "inventar": table } }, { "new": true }, function(err,doc) { console.log( doc ); // shows the modified document callback(err) } ); 产生TypeError: undefined is not a function at D:\straff_alpha\routes\routes.js:177:18
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多