I have these two models:
Student
{
"name": "student",
"plural": "students",
"base": "User",
"idInjection": false,
"options": {
"validateUpsert": true
},
"relations": {
"test": {
"type": "embedsMany",
"model": "test",
"property": "mytest",
"options": {
"validate": true,
"forceId": false
}
}
}
and
Test
{
"name": "test",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
}
}
}
When I try to create a new test I get this error
Error: Invalid reference: undefined
I create the test in this way:
Student.js
studentInstance.test.add({text : "something "})
What am I doing wrong?
Update
Delete in embedsMany
update id in test.
Student.js
Student.show = function(email, cb) {
Student.findById(email,function(err, student) {
...
var tmp = student.mytest;
for (var i = 0; i < tmp.length; i++) {
student.test.destroy(tmp[i].id);
}
})
...
}
I tried with
destroy not work correctly, not always remove the data
and
remove show this error
Error: Invalid reference: undefined
at EmbedsMany.remove
Update
Added a example of db
{
"_id": "value",
"property1": "value",
.
.
"mytest": [
{
"text": "something",
"creation": {
"$date": "2016-08-23T14:31:44.678Z"
},
"id": "d738253472876b17feb4b46b"
}
]
}
You don't have test model.
In test.json you defined its names as notification => "name": "notification",
UPDATE
For building (without persisting) an embedded instance please use studentInstance.test.build({text : "something "})
and for creating (with persisting) that please use studentInstance.test.create({text : "something "})
After 3 years, I've faced with same problem by using remove, destroyById.
And then I use unset method. It works.
Person.findById(body.metadata.person.id, (err, person) => {
person.creditCards.unset(
body.creditCard.id,
(err, res) => {
}
);
}
This works well.
Related
I'm trying to fetch data from an AWS DataExchange provider based on their company's API specification.
I'm using the AWS Node.JS NPM modules 'aws-sdk' and '#aws-sdk/client-dataexchange'.
However, every query I've written is returning the error '404: Asset not found'.
I'm subscribed to use the API and I've verified that all my AWS credentials, policies and IAM keys give me permission to access the API.
Could someone please help me identify what's wrong with my query in relation to the API specification.
Thanks!
The response I get looks like below:
404: Asset not found
'$fault': 'client',
'$metadata': {
httpStatusCode: 404,
requestId: 'b7e6e691-xxxxxxx7657201138a4',
extendedRequestId: undefined,
cfId: 'dBQBwlCE8cXp4--xxxxxxxxxxx3j2lTfxywUezCPEA6nusJCJg==',
attempts: 1,
totalRetryDelay: 0
},
ResourceType: 'ASSET',
ResourceId: 'e055c882bde1fa3xxxxxxxxx'
}
My current request 'body' looks like below:
Body: JSON.stringify({
"description": "GraphQL query for the Ursa Space Imagery Catalog.",
"content": {
"application/graphql": {
"schema": {
"$ref": "#/components/schemas/CatalogSearchRequest"
},
"query": {
"description": "Limit the number of records in a response.",
"value":"{\n availablemetadatarecord(\n limit: 20\n content: { catalogProperties: { vendor: { eq: \"ICEYE\" } } }\n ) {\n assignedId\n }\n}\n"
}
}
},
"required": true
}),
The DataExchange provider's actual API specification looks like below:
{
"openapi": "3.0.1",
"info": {
"title": "image-services",
"description": "API Gateway for integration of Platform Services into AWS Data Exchange",
"version": "2022-03-03T20:04:18Z"
},
"servers": [
{
"url": ""
}
],
"paths": {
"/psdm/graphql": {
"post": {
"requestBody": {
"description": "GraphQL query for the Catalog in the form of:\n\n `{\n availablemetadatarecord(\n QUERYPARAMS\n ) { \n FIELDLIST\n } \n }`\n",
"content": {
"application/graphql": {
"schema": {
"$ref": "#/components/schemas/CatalogSearchRequest"
},
"examples": {
"Limit returned data": {
"description": "Limit the number of records in a response.\n\nIn your query, simply specify `limit: <int>` \n",
"value": "{\n availablemetadatarecord(\n limit: 10\n content: { catalogProperties: { vendor: { eq: \"EYE\" } } }\n ) {\n assignedId\n }\n}\n"
}
}
}
},
"required": true
},
"responses": {
"200": {
"description": "200 response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CatalogSearchResponse"
}
}
}
}
},
"security": [
{
"sigv4": []
}
]
}
}
},
"components": {
"schemas": {
"CatalogSearchRequest": {
"title": "CatalogSearchRequest",
"type": "object"
},
"CatalogSearchResponse": {
"title": "Catalog Search Response",
"required": [
"data",
"paginationInfo"
],
"type": "object",
"properties": {
"paginationInfo": {
"type": "object",
"properties": {
"recordsInPage": {
"type": "integer"
},
"nextOffset": {
"type": "integer"
}
}
},
"data": {
"type": "object",
"properties": {
"availablemetadatarecord": {
"type": "array",
"description": "Records returned by query",
"items": {
"type": "object"
}
}
}
}
}
}
},
"securitySchemes": {
"sigv4": {
"type": "apiKey",
"name": "Authorization",
"in": "header",
"x-amazon-apigateway-authtype": "awsSigv4"
}
}
}
}
I saw a few questions like mine but couldn't find any solutions that worked so I thought I'd ask.
I'm trying to pull all my data from my database so I can select parts of it in my app. I had my database working fine but when I tried to pull the pictures it failed and keeps giving me this error and also does not seem to receive the data from the database:
app.model.users.find((err,result)=>{
^
TypeError: Cannot read property 'find' of undefined
Here is my code:-
server.js:-
'use strict';
const loopback = require('loopback');
const boot = require('loopback-boot');
const app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
const baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
const explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
console.log(Object.keys(app.models));
app.model.users.find((err,result)=>{
if(result.length ===0){
const user={
email:'jhanvi#gmail.com',
password:'jhanvi',
username: 'jhanvi',
};
app.models.user.create(user,(err,result)=>{
console.log("tried to create user ",err,result);
});
}
});
app.models.user.afterRemote('create', (ctx,user,next) =>{
console.log("new user is",user);
app.models.Profile.create({
first_name: user.username,
created_at: new Date(),
userId: user.id
},(err,result)=>{
if(!err && result){
console.log("created new profile",result);
}
else{
console.log("there is an error ",err);
}
});
next();
});
user.json:-
{
"name": "user",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
},
"validations": [],
"relations": {
"Profile": {
"type": "hasMany",
"model": "Profile",
"foreignKey": ""
},
"accessTokens":{
"type":"hasMany",
"model":"CustomAccessToken",
"foreignKey":"userId"
}
},
"acls": [],
"methods": {}
}
Profile.json :-
{
"name": "Profile",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
},
"created_at": {
"type": "date"
},
"age": {
"type": "number"
},
"history": {
"type": [
"object"
]
}
},
"validations": [],
"relations": {
"user": {
"type": "belongsTo",
"model": "user",
"foreignKey": "userId"
}
},
"acls": [],
"methods": {}
}
In your model you refer to user.
app.model.users.find((err,result)
should then surely be
app.model.user.find((err,result)
(i see you seem to be using both versions...)
I am looking a way to open a particulate addcase on addcase page from Event Action , i was trying with "icm.OpenPage"
try{
solution.retrieveCaseType("Demo_ApprovalCase", function(caseType) {
solution.createNewCaseEditable(caseType, function(pendingCaseEditable) {
modified_payload = {
caseEditable: pendingCaseEditable,
caseType: caseType,
coordination: new icm.util.Coordination(),
eventName: "icm.SendNewCaseInfo",
eventType: "broadcast"
};
var subject = new dojox.uuid.Uuid(dojox.uuid.generateRandomUuid());
var targetosname = solution.targetObjectStore.objectStoreName;
self.onBroadcastEvent(icm.OpenPage, {
pageClassName: "CMTOS/Demo/CRDemo",
pageType: "caseNewPage",
subject: subject,
pageTitle: "Add Case Custom",
pageContext: {
solution: self.solution,
role: self.role
},
crossPageEventName: "icm.SendNewCaseInfo",
crossPageEventPayload: modified_payload
});
});
});
}catch (Error) {
console.log(Error);
}
I got a error saying "eventName is undefined".
I have try with "icm.OpenAddCasePage" event to get this result by with the example i found
{"ICM_ACTION_COMPATIBLE": true,
"context": null,
"name": "Custom Add Case Action",
"description": "An action to add cases from other solution",
"properties": [
{
"id": "label",
"title": "Add a custom Case",
"defaultValue": "Custom Add Case",
"type": "string",
"isLocalized":false
},
{
"id": "solution",
"title": "Solution",
"type": "string",
"isLocalized":false
},
{
"id": "caseType",
"title": "Case Type",
"defaultValue": "",
"type": "string",
"isLocalized":false
}
],
"events":[
{
"id":"icm.OpenAddCasePage",
"title":"Open Add custom Case Page",
"direction":"published",
"type":"broadcast",
"description":"Open Add Custom Case Page"
}
]
};
But i didn't get any output.I am looking a way to do BroadcastEvent or call function so i can open a particulate addcase.
I'm starting to study loopback.
I created my app, and below this model:
{
"name": "movimenti",
"plural": "movimenti",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"mov_id": {
"type": "number",
"required": true
},
"mov_tipo": {
"type": "string",
"required": true
},
"mov_valore": {
"type": "number",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
I connected the model to my MySQL DB:
"movimenti": {
"dataSource": "banca",
"public": true
}
I launched the application, and went to the address indicated.
I questioned the GET method, having this error:
"stack": "Error: ER_BAD_FIELD_ERROR: Unknown column 'id' in 'field list'\n
but I do not have an ID field in my table.
How can I fix this problem?
Loopback will automatically add an id column if none of the properties of a model is mentioned as id.
Assuming for your model, property mov_id is the id. Define so in the model by adding id: true line: Reference
{
...
"properties": {
"mov_id": {
"type": "number",
"required": true,
"id":true
},
...
}
I am quite new to Loopback and NodeJS, so please tell me if there is a "Node way" of doing something that I am missing. I decided to write a basic application to try and learn more.
I have two models, 'UserInformation' and 'ClothingArticle'. I have created a 'hasMany' relation from UserInformation to ClothingArticle.
As a basic test, I wanted to add a remote method to UserInformation to get recommendations for ClothingArticles. However, I cannot seem to get access to anything related to ClothingArticles. I added code into the common/models/user-information.js file to try and retrieve information about the relation, but am not sure if this is even the right spot to be putting it.
My code is below, could you help?
common/models/user-information.js:
module.exports = function(UserInformation) {
get_methods = function(obj) {
var result = [];
for(var id in obj) {
try {
if(typeof(obj[id]) == "function") {
result.push(id + " (function): "); //+ obj[id].toString());
}
else
result.push(id + ": "); // + obj[id].toString());
}
catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
// This doesn't anything about my new relations?
console.log(get_methods(UserInformation.prototype));
UserInformation.recommendations = function(source, callback) {
var response = "I don't have any recommendations.";
var test_function = UserInformation.findById(3, function(err, instances) {
if(err) return console.log("Errors: " + err);
console.log("Instances: " + String(instances));
// Nothing here either about the relations.
console.log(get_methods(UserInformation));
console.log(UserInformation.app);
/*
instances.clothingArticles.create({
id:92,
colors:['red','blue']
});
*/
console.log("Created a new clothing article.");
});
console.log (response);
callback(null, response);
}
UserInformation.remoteMethod(
'recommendations',
{
accepts: [
{arg: 'source', type: 'string'} // Used to mark the source (closet, generic, etc)
],
http: {path: '/recommendations', verb: 'get'},
returns: {arg: 'recommendations', type: 'string'}
}
);
};
common/models/user-information.json:
{
"name": "UserInformation",
"base": "PersistedModel",
"strict": false,
"idInjection": false,
"properties": {
"birthday": {
"type": "date"
},
"id": {
"type": "number",
"id": true,
"required": true
},
"eye_color": {
"type": "string"
},
"hair_color": {
"type": "string"
},
"weight": {
"type": "string",
"comments": "pounds"
},
"height": {
"type": "number",
"comments": "inches"
}
},
"validations": [],
"relations": {
"clothingArticles": {
"type": "hasMany",
"model": "ClothingArticle",
"foreignKey": "owner_id"
}
},
"acls": [],
"methods": []
}
common/models/clothing-article.json:
{
"name": "ClothingArticle",
"base": "PersistedModel",
"strict": false,
"idInjection": false,
"properties": {
"id": {
"type": "number",
"id": true,
"required": true
},
"colors": {
"type": [
"Color"
],
"required": true
},
"owner_id": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
I suggest starting with our getting started example and working your way through through the tutorial series here: https://github.com/strongloop/loopback-example
The questions you ask are answered throughout the examples (ie. model relations). To answer your question, if you defined a relation properly, you should be able to access the relation via dot.
...
UserInformation.ClothingArticle...
...
See http://docs.strongloop.com/display/LB/HasMany+relations for more information.