Mongoose
view release on metacpan or search on metacpan
lib/Mongoose/Engine.pm view on Meta::CPAN
}
else {
if ( ref Mongoose->class_config($self)->{pk} ) {
# if we have a pk and no _id, we must have a new
# document, so we insert to allow the pk constraint
# to ensure uniqueness; the 'safe' parameter ensures
# an exception is thrown on a duplicate
my $id = $coll->insert_one( $doc )->inserted_id;
$self->_id( $id );
return $id;
}
else {
# save without pk
my $id = $coll->insert_one( $doc )->inserted_id;
$self->_id( $id );
# if there are any new, unsaved, documents in the scope,
# we have circular relation between $self and @scope
my @unsaved;
for my $x ( @scope ) {
unless( $x->_id ) {
push @unsaved, $x;
}
}
if (@unsaved) {
while ( my $x = pop(@unsaved) ) {
$x->_save(@unsaved);
}
$self->_save;
}
return $id;
}
}
}
sub _get_blessed_type {
my ($self,$type) = @_;
my $class = $type->name or return;
my $parent = $type->parent;
return $class unless defined $parent;
return $class if $parent eq 'Object';
return $parent->name;
}
# shallow delete
sub delete {
my ( $self, $args ) = @_;
if ( ref $args ) {
return $self->collection->remove($args);
}
elsif ( my $pk = $self->_primary_key_query ) {
return $self->collection->delete_one($pk);
}
return undef;
}
#sub delete_cascade {
# my ($self, $args )=@_;
# #TODO delete related collections
#}
sub db {
my $self=shift;
return Mongoose->connection( ref $self || $self )
|| croak 'MongoDB database need to be configured. Set Mongoose->db(...) first';
}
sub collection {
my $self = shift;
$self->db->get_collection( $self->_collection_name );
}
sub _primary_key_query {
my ( $self, $hash ) = @_;
my @keys = @{ Mongoose->class_config($self)->{pk} || ['_id'] };
my @pairs = map { $_ => $self->{$_} } grep { $self->{$_} } @keys;
# Query need to have all pk's
return {@pairs} if @pairs == @keys * 2;
}
sub _collection_name { Mongoose->class_config(shift)->{collection_name} }
sub find {
my $self = shift;
my $cursor = bless $self->collection->find(@_), 'Mongoose::Cursor';
$cursor->_collection_name( $self->_collection_name );
$cursor->_class( ref $self || $self );
return $cursor;
}
sub query {
my $self = shift;
$self->collection->_warn_deprecated( 'query' => ['find'] );
$self->find(@_);
}
sub find_one {
my $self = shift;
if( @_ == 1 && ( !ref($_[0]) || ref($_[0]) eq 'BSON::OID' ) ) {
my $query = { _id=> ref $_[0] ? $_[0] : eval{BSON::OID->new( oid => pack("H*",$_[0]) )}||$_[0] };
if ( my $doc = $self->collection->find_one($query) ) {
return $self->expand( $doc );
}
}
else {
my ($query,$fields, $scope) = @_;
if ( my $doc = $self->collection->find_one( $query, $fields ) ) {
return $self->expand( $doc, $fields, $scope );
}
}
undef;
}
sub count {
my $self = shift;
( run in 1.044 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )