First of all I'm new to laravel mongodb collection using jenssegers in laravel 5.0 . I would like to form a collection inside sub collection like below
{
"Uid": 1112,
"AccountNo": 7620424,
"Party": {
"LanguageCode": "en",
"Type": "individual",
"Contact": [
{
"id" : It will be mongo object id How to create?
"Type": "default",
"Person": {
"FullName": "Test Test"
},
{
"id" : It will be mongo object id How to create?
"Type": "default",
"Person": {
"FullName": "Test Test"
},
"MessagingMedium": [
{
"Id": It will be mongo object id How to create?
"Scheme": "mailto",
"URI": "demo1dd122#gmail.com",
"Status": "awaiting.registration"
},
{
"Id": It will be mongo object id How to create?
"Scheme": "mailto",
"URI": "demo1dd122#gmail.com",
"Status": "awaiting.registration"
}
]
}
]
},
}
I have userprofile model
use Jenssegers\Mongodb\Model as Eloquent;
class UserProfile extends Eloquent {
protected $table = 'user_profile';
}
use Jenssegers\Mongodb\Model as Eloquent;
class Contact extends Eloquent {
protected $table = 'contact';
}
I have trying to create user profile after trying to add contacts subcollection to that created userprofile collection like below
$user = UserProfile::create(array('Uid' => $uId, 'AccountNo' => $accNo));
$card = Contact::create(['id' => 123]); //contact mongodb Eloquent
$card->userprofile()->save($card);
But its not working and the collection is not creating
Is that correct and i dont know abount hasmany, embedsmany colleciton
Anyone help me out
You have to use the embedsMany relation. This relation allows you to save arrays of objects (Eloquent objects with their own IDs) into existing documents. The relation will be completely managed by the ORM.
You can declare it like that :
class UserProfile extends Eloquent
{
// No table declaration because this model is only saved in the contact collection
}
class Contact extends Eloquent
{
protected $table = 'contact';
public function userProfiles()
{
return $this->embedsMany('UserProfile');
}
}
If you want to embed only one object into an other, you can use the embedsOne relation.
And, before that, you should take a serious look at the package documentation ;)
Related
I want to update or delete a particular field (subTags:) in an array of objects.
{
"_id": {
"$oid": "63c175a0ec5dac10b35ac9da"
},
"name": "clerk",
"description": "clerical duties including typing and filing.",
"tags": "assistant receptionist typist ",
"__v": 0,
"subCategory": [
{
"name": "tele-clerk",
"subTags": [
"assistant",
"receptionist"
]
},
{
"name": "administrative-clerk",
"subTags": [
"assistant",
"receptionist",
"typist"
]
}
]
}
I tried using :
const updatedSubCategory = await this.categories.findOneAndUpdate({name:category.name,"subCategory.name": category.subCategory.name},{ $addToSet:{subCategory: category.subCategory}},{new:true})
but it is creating another new object inside subcategory array of same name I don't want that to happen.The name field in the subcategory must be unique.
my schema is :
#Schema({collection:'category'})
export class SubCategorySchema {
#Prop({unique:true})
name:string
#Prop()
tags:string[]
}
#Schema({collection:'category'})
export class CategorySchema {
#Prop({unique:true, lowercase:true})
name:string
#Prop({lowercase:true})
subCategory:SubCategorySchema[]
#Prop({lowercase:true})
description:string
#Prop({lowercase:true})
tags:string
}
Below is the sample of my Mongo-collection data-structure
{
"id": "5d91fe25da1917111182ce5a",
"customName": "Chess Application",
"status":"not_ready",
"environments": [
{
"environmentId": "6bbbbda6-b01a-4b9e-99d5-a1d0f696449a",
"environmentName": "Dev",
"environmentType": "dev",
},
{
"environmentId": "3b958d27-8fb7-4edd-bbb0-1dd86437d313",
"environmentName": "qa",
"environmentType": "qa",
}
]
}
Am using spring-JPA to get the data.. I will get only the environmentId as input and i will scan all the collections and get the collection that has this environmentId
Note: the Environment-id here is not mongo-created ID. It is the UUID generated by my Java app during insertion
i used findByEnvironmentsIsIn() method and it is not helpful . Any idea on how to get only one object from the list-of-sub-documents ?
#Query("{'environments' : { $elemMatch: { 'environmentId': { $in: ?0 }}}}")
List<Object> findByEnvironmentsIsIn( Set<String> environmentIds);
I guess this should work for you
My app has a "Categories" model.
Categories can be children of other categories.
So there is a "CategoriesAssociations" model.
Here is the code :
/* api/models/Categories.js */
module.exports = {
attributes: {
name: {
type: "string"
},
parents: {
collection: "categoriesassociations",
via: "child"
},
children: {
collection: "categoriesassociations",
via: "parent"
}
}
}
/* api/models/CategoriesAssociations.js */
module.exports = {
attributes: {
parent: {
model: "categories"
},
child: {
model: "categories"
}
}
}
Now when I use the find route aka /categories I get this :
[
{
"createdAt": "2015-08-24T14:16:46.662Z",
"updatedAt": "2015-08-24T14:24:23.819Z",
"name": null,
"id": "55db274e424996cc7e7512e2"
},
{
"createdAt": "2015-08-24T14:18:29.748Z",
"updatedAt": "2015-08-24T14:18:41.105Z",
"name": "test",
"id": "55db27b5424996cc7e7512e4"
}
]
So no trace of the parents and children properties.
The associations are indeed created in the database for when I request /categories/55db27b5424996cc7e7512e4/children I get this :
[
{
"parent": "55db27b5424996cc7e7512e4",
"child": "55db274e424996cc7e7512e2",
"createdAt": "2015-08-24T14:32:43.429Z",
"updatedAt": "2015-08-24T14:32:43.429Z",
"id": "55db2b0bc97cc73083017f60"
}
]
Sails docs states that the populate configuration key for blueprints defines :
Whether the blueprint controllers should populate model fetches with data from other models which are linked by associations. If you have a lot of data in one-to-many associations, leaving this on may result in very heavy api calls.
The value is true in my project but still, associations attributes don't get populated.
Did I misunderstand the docs or is there a problem with my project?
I use sails 0.11.x
The problem is I'm using sails-permissions which has overrides blueprints' populate config :
sails.config.blueprints.populate = false;
I opened an issue to know why it's done globally and how to fix the problem.
I am using couchbase and I have a document (product) that looks like:
{
"id": "5fe281c3-81b6-4eb5-96a1-331ff3b37c2c",
"defaultName": "default name",
"defaultDescription": "default description",
"references": {
"configuratorId": "1",
"seekId": "1",
"hsId": "1",
"fpId": "1"
},
"tenantProducts": {
"2": {
"adminRank": 1,
"systemRank": 15,
"categories": [
"3"
]
}
},
"docType": "product"
}
I wish to get all products (this json is product) that belong to certain category, So i've created the following view:
function (doc, meta) {
if(doc.docType == "product")
{
for (var tenant in doc.tenantProducts) {
var categories = doc.tenantProducts[tenant].categories
// emit(categories, doc);
for(i=0;i<categories.length;i++)
{
emit([tenant, categories[i]], doc);
}
}
}
}
So i can run the view with keys like:
[["tenantId", "Category1"]] //Can also have: [["tenant1", "Category1"],["tenant1", "Category2"] ]
My problem is that i receive the document, but i wish to sort the documents by their admin rank and system rank, these are 2 fields that exists in the "value".
I understand that the only solution would be to add those fields to my key, determine that my key would be from now:
[["tenantId", "Category1", "systemRank", "adminRank"]]
And after i get documents, i need to sort by the 3rd and 4th parameters of the key ?
I just want to make sure i understand this right.
Thanks
I have one document in my "params" collection like this:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": ObjectId("4d120a2d2b8d8d3010000000"),
"$db": "test"
}
]
}
the referenced document is this:
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
I'm using DoctrineODM to fetch the "param" documents which referenced "productType" is "car". I'm using this code:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
but the result is an empty array. How can i do this?
If you using ReferenceMany or ReferenceOne you can't query by any reference document field, except reference document id.
If you need query on code from referenced collection you should use EmbedMany instead of ReferenceMany.
In this case your document will be:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
]
}
And following query will work:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
Also if your ProductType code is unique you can use it instead of MongoId, in this case you can query on $id:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": 'car',
"$db": "test"
}
]
}
Referenced document:
{
"_id": 'car'
}
Query:
$query->field('productTypes.$id')->equals('car');
You must use the references() method of Query Builder for a #MongoDB\ReferenceOne like https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html
$productType = $dm->getRepository('Cms\Model\ProductTypes')->findOneByCode('car');
$queryBuilder = $dm->getRepository('Cms\Model\Param')->createQueryBuilder()
->field('productTypes')->references($productType);
$results = $queryBuilder->getQuery()->execute();
PS: use includesReferenceTo() a #MongoDB\ReferenceMany
->field('productTypes.code')->equals(new \MongoRegex('/.*car.*/i'))