在现有文档中插入数组 [英] Insert Array in existing Document

查看:67
本文介绍了在现有文档中插入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件:

  _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,
接受:0
},
{
ean:1,
name:name1,
runtime:0,
art:null,
marker :null,
stammkost:null,
接受: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,
'接受'=>'0'
/ /)
);
尝试{
$ collection-> update(array(tablename=> $ tablename),array('$ push'=> array(inventar=> $ new_data)) );
echo json_encode($ collection);
}
catch(MongoConnectionException $ e){
echo'< p>更新失败< / 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 null null 
{ok:0,n:0,nModified:0}
IWEO_IWBB_01062015 2 name2 null null
{ok: 0,n:0,n修改:0}

为什么不更新/插入?这是错误的命令?

解决方案

这里的代码有些问题。首先要注意的是,您现在正在异步环境中运行,并且需要改变对如何执行某些操作的思考。



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



您不能使用基本控制循环,其中包含异步执行的函数。相反,一旦异步函数update实际返回结果,您需要能够调用循环的下一次迭代(或者至少表示单次迭代完成的信号)。



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



以下内容类似于原始PHP列表,但针对异步方法进行了调整,也使用了 async.eachSeries nofollow> async 库:

  async.eachSeries (
表,
函数(表,回调){
var tablename = table.tablename;
delete table.tablename; //只需删除密钥而不是重构
OutAccept.update(
{tablename:tablename},
{$ push:{inventar:table}},
function(err,numAffected){
console.log(numAfftected); //告诉您有多少更新或没有更新
回调(错误)
}
);
},
函数(错误){
//完成所有数组项后来这里
}
);

.findOneAndUpdate()命令返回只有在您要求 {new:true}



<$时才修改并修改的文档p $ p> async.eachSeries(
表,
函数(表,回调){
var tablename = table.tablename;
delete table.tablename ;
OutAccept.findOneAndUpdate(
{tablename:tablename},
{$ push:{inventar:table}},
{new:true },
函数(错误,doc){
console.log(doc); //显示修改后的文档
callback(err)
}
);
},
函数(错误){
//完成所有数组项后来到这里
}
);

如果你想一次添加多个数组元素,或者你想直接添加一个元素然后使用 $ each 的code> 修饰符 $ push

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


OutAccept.update(
{tablename:tablename},
{$ push:{inventar:{$ each:inventar },}
函数(错误,数字受影响){
//在这里工作
}
);


I have a document like this:

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

and want to add array like this:

"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"
    }
],

In my old PHP-Server I used the code below to insert it. The right command is "update". In node.js it seems to be another command.

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();
    }           
}

In my new node.js I use the code below:

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();
    //}
    });

});

The output in console is:

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 }

Why it isnt updated/inserted? Its the wrong command?

解决方案

There are a few things wrong in your code here. First and foremost to note is that you are running in an "async" environment now and you need to change the thinking on how you do some things.

Your previous PHP code is "blocking", which means that every line of code must complete before moving on to the next line of code. This includes waiting for a database server to perform an update and return the response.

You cannot use basic control loops with functions inside them that perform asynchronously. Instead you need something that can call the next iteration of the loop (or at least signal that a single iteration is complete ) once the asynchronous function "update" has actually returned a result.

The second point here is that "nothing updated" because you did not tell the function what to update or what to update the matched document with.

The following is analogous to you original PHP listing, but adjusted for "async" methods also use the async.eachSeries for the loop control from the async library:

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
    }
);

The .findOneAndUpdate() command instead returns the document that was modified and with the modifications only if you ask for them with { "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
    }
);

If you want to add Multiple array elements at once, or if you have even a single element directly in an array then use the $each modifier to $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
    }
);

这篇关于在现有文档中插入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆