2011-03-29 60 views
1

使用下面的代码,删除指定的文件。Perl mongodb删除记录问题

sub delete_post{ 
my $post_id = shift; 
my $post_to_delete = $posts->find_one({"_id" => $conn->oid($post_id)})->{_id}; 
$posts->remove({"_id" => $post_to_delete}); 

}

如果使用此代码:

sub delete_post{ 
my $post_id = shift; 
$posts->remove({"_id" => $conn->oid($post_id)}); 

}

删除所有文件。

mongodb是否无法接受oid作为删除文档的标准?

+0

为什么你需要'$ conn-> oid'?以下不起作用? '$ posts-> remove({“_ id”=> $ post_id});' – 2011-03-29 23:28:31

+0

灾难。第一种方法,随机删除一个文件或删除所有文件。第二种方法,删除没有。 – Weiyan 2011-03-30 00:03:11

+0

[链接](http://stackoverflow.com/questions/5480645/pel-mongo-coll-find-one-id-xxxx-method-not-function-as-expected)是另一个关于不安全使用_id作为关键的问题在find方法中。 – Weiyan 2011-03-30 00:43:43

回答

2

使用MongoDB :: OID方法创建_id对象而不是$ conn-> oid;

sub delete_post{ 
my $post_id = shift; 
my $oid = MongoDB::OID->new(value => $post_id); 
$posts->remove({"_id" => $oid}); 
$db->log->insert({"removed_post" => $post_id}); 

}