I have a contact form where i can able to save the data in the database using loopback3. I need to send an email also so i have added the email connector for this module, but i can able to send only the static values in the mail. How to get the dynamic values in contact.js file and send through email.
contact.json
{
"name": "contact",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"id": {
"type": "number"
},
"name": {
"type": "string",
"required": true
},
"email": {
"type": "string",
"required": true
},
"subject": {
"type": "string",
"required": true
},
"message": {
"type": "string",
"required": true
},
"inserted_date": {
"type": "string"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
contact.js
'use strict';
const app = require('../../server/server');
module.exports = function(Contact) {
Contact.afterRemote('create', function(context, remoteMethodOutput, next) {
next();
Contact.app.models.Email.send({
to: 'lakshmipriya.l#company.com',
from: 'lakshmipriya.l#gmail.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
});
};
How to send an email with dynamic values, can anyone tell me how to fetch the contact.json values and send to contact.js file .
You can access the model instance through the context object, which transports the data. You can read more on it here: https://loopback.io/doc/en/lb2/Remote-hooks.html#ctxresult
So to send the email to the contact that has been created:
Contact.app.models.Email.send({
to: context.result.email,
from: 'lakshmipriya.l#gmail.com',
subject: 'my subject',
text: 'my text',
html: 'my <em>html</em>'
}, function(err, mail) {
console.log('email sent!');
cb(err);
});
});
Related
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'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
},
...
}
Upon using Postman when I try to POST an answer to the questions id it gives a 400 Bad Request error and it seems to be a validator error. Here is the POST request JSON data I am sending. It has been a long day and still havent been able to figure this out. Below I am listing my Schema and routes.
I am also using packages such as body-parser and node-restful
{
"aTitle": "THIS IS A TEST",
"aBody": "This is a body test"
}
{
"message": "Questions validation failed",
"name": "ValidationError",
"errors": {
"answers.aBody": {
"message": "Path `answers.aBody` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "answers.aBody"
},
"kind": "required",
"path": "answers.aBody"
},
"answers.aTitle": {
"message": "Path `answers.aTitle` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "answers.aTitle"
},
"kind": "required",
"path": "answers.aTitle"
},
"qBody": {
"message": "Path `qBody` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "qBody"
},
"kind": "required",
"path": "qBody"
},
"qTitle": {
"message": "Path `qTitle` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "qTitle"
},
"kind": "required",
"path": "qTitle"
}
}
}
// Dependencies
var restful = require('node-restful');
// Database
var mongoose = restful.mongoose;
var Schema = mongoose.Schema;
// Question Schema
var QuestionSchema = new Schema({
qTitle: {
type: String,
required: true
},
qBody: {
type: String,
required: true
},
created_at: {
type: Date
},
updated_at: {
type: Date
},
// Relationship to the Question or child of the question
answers: {
aTitle: {
type: String,
required: true
},
aBody: {
type: String,
required: true
},
created_at: Date,
updated_at: Date
}
});
// Export the question schema
module.exports = restful.model('Questions', QuestionSchema);
'use strict';
var express = require('express');
var router = express.Router();
var Question = require('../models/question');
Question.methods(['get', 'put', 'post', 'delete']);
Question.register(router, '/questions');
Question.register(router, '/questions/:id/answers');
// Exports the router
module.exports = router;
According to the error message and the question schema (look at the ones that have required: true), the POSTed request JSON data you need to send is at least like this:
{
"qTitle": "this is question title",
"qBody": "this is question body",
"answers": {
"aTitle": "THIS IS A TEST",
"aBody": "This is a body test"
}
}
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.
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.