Node update not working, format is wrong while send to api - node.js

I try to update my data from Angular to Node.js
component.ts
updatefunction(id,data){
console.log("component",data);
//component {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
this.uAdminService
.updateUser(id,data).subscribe(
result => {
//console.log(result.json());
},
error => {
console.log(error.json());
}
);
}
in myservice.ts
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
my nodejs controller
router.put('/:id', VerifyToken, function (req, res) {
console.log(req.body);
//{'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'}
User.findByIdAndUpdate({_id:req.params.id}, req.body, {new: true}).select("-password")
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving Report."
});
});
});
my req.body console like this {'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'} but i pass from angularjs in this format {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
I don't know why it's converting so that it's not update to db
if i console from api it will like this { name: "Test",email: "test123#gmail.com"}

Update myservice.ts like below:
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123#gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
Changed the Content-Type to application/json as you are sending a json formatted data and not form data.

Related

Store Json object in mongoDb with fetch request

I have a User model and trying to add education field to mongoDB as json object as follows,
User model
education: {
"school": String,
"years":Number
},
Client
//add Education section
const updateEducation = async (e) => {
e.preventDefault();
await fetch(`http://localhost:5000/api/user/updateEducation`, {
method: "PUT",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
educationYearText: EducationYear}),
})
.then((res) => res.json())
.then((data) => {
console.log("User education is:", data.education +""+data.educationYear);
});
};
Server
const updateEducation = async (req, res) => {
try {
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$set: {
'education.school': req.body.educationSchool,
'education.years': req.body.educationYearText,
},
}
);
if (!user) {
res.status(404).json("user not exist");
}
res
.status(200)
.json({
education: user.education.School,
educationYear: user.education.years,
});
} catch (error) {
res.status(500).send({ error: error.message });
}
};
When im hitting this endpoint in postman http://localhost:5000/api/user/updateEducation
{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}
Im getting {
"error": "Plan executor error during findAndModify :: caused by :: Cannot create field 'school' in element {education: []}"
}
Whats wrong?
You should $push into an array:
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$push: {
education: {
school: req.body.educationSchool,
years: req.body.educationYearText,
}
},
},
{ new: true }
);

Finding items with attribute value match excluding another value in Sequelize

I have this code :
module.exports.MyFunction= async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let email = decoded.email;
let data = req.body;
let searchUser = data.user;
try {
let user = await User.findAll({
where: {
[Op.or]: [
{ firstName: searchUser },
{ lastName: searchUser },
{ email: searchUser },
{ publicKey: searchUser },
],
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};
If I run that code, I get all the users that match with the value passed in searchUser.
What I want to do is to exclude the user object that have a specific email.
For instance, if have multiple users named Michel, I want to get all the users with an email address different of the email variable declared at the top of the function, even if their fisrtName matches.
Problem solved by doing this :
module.exports.MyFunction = async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let loggedUserEmail = decoded.email;
let data = req.body;
let searchUser = data.user;
console.log(searchUser);
try {
let user = await User.findAll({
where: {
[Op.or]: [
{
firstName: {
[Op.startsWith]: searchUser,
},
},
{
lastName: {
[Op.startsWith]: searchUser,
},
},
{
email: {
[Op.startsWith]: searchUser,
},
},
{
publicKey: {
[Op.startsWith]: searchUser,
},
},
],
email: {
[Op.ne]: loggedUserEmail,
},
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};

How to send react native text field value as JSON.stringify

I have code like this:-
export default class TextField extends Component {
constructor(props) {
super(props);
this.state = {
userID: '',
userName: '',
userGmail: '',
userTNumber: '',
};
}
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
} <TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={userID => this.setState({userID})}
value={this.state.userID}
autoCapitalize="none"
/>
</View>
}
I Need To Send My Text Input To My Node BackEnd...
I Don't Know How To Send My Data Using This Fetch Function
**
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
};
**
I Don't Know How To Put My Text Input Into,
body: JSON.stringify({}),
This Is My BackEnd To Post My Data:-
app.post('/send-data', (req, res) => {
const customer = new Customer({
userID: req.body.userID,
userName: req.body.userName,
userGmail: req.body.userGmail,
userTNumber: req.body.userTNumber,
});
customer
.save()
.then(result => {
console.log(result);
res.send(result);
})
.catch(err => {
console.log(err);
});
});
Can You Help Me ..?
ThankYou..!
If I understood correctly, you want to pass your data in the following format:
{
"userID": 1,
"userName": "John Doe",
"userGmail": "john.doe#example.com",
"userTNumber": "1234"
}
You want to use the data from your state and pass it to the fetch function, like so:
export default class TextField extends Component {
constructor(props) {
super(props)
this.state = {
userID: "",
userName: "",
userGmail: "",
userTNumber: "",
}
}
addCustomer = () => {
const { userID, userName, userGmail, userTNumber } = this.state
fetch("http://localhost:3000/send-data", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userID, userName, userGmail, userTNumber }),
})
}
render() {
return (
<TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={(userID) => this.setState({ userID })}
value={this.state.userID}
autoCapitalize="none"
/>
)
}
}

Returning responses from got (requests) to an object for callback

I am using got module to make POST requests to get data.
I am wanting to synchronously call 3 APIs, get the response objects, then callback. I am having trouble getting returning the response to callback object. It is returning {} instead of the actual response. I would also like to make all of these calls synchronously so that the requests are occurring simultaneously to save time.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":2,
"color":"blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item":3,
"size":"large",
}
}
}).json();
}
callback(null,{
"DATA1": getDATA1(),
"DATA2": getDATA2(),
"DATA3": getDATA3(),
});
};
The response I am getting is
{
"DATA1": {},
"DATA2": {},
"DATA3": {}
}
The response I am expected/ want is something like this
{
"DATA1": {
"available_f":"Y"
},
"DATA2": {
"available_f":"N"
},
"DATA3": {
"available_f":"Y"
},
}
Those async functions will need to be awaited so you would need to do something like this that will wait till all of the requests have resolved and then you can gather the results and return them through the callback.
const got = require('got');
exports.handler = (event, context, callback) => {
async function getDATA1() {
return await got.post('https://url.com/serviceapi/1/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 1,
}
}
}).json();
}
async function getDATA2() {
return await got.post('https://url.com/serviceapi/2/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 2,
"color": "blue",
}
}
}).json();
}
async function getDATA3() {
return await got.post('https://url.com/serviceapi/3/', {
responseType: 'json',
resolveBodyOnly: true,
username: 'user',
password: 'pass',
json: {
"Input": {
"item": 3,
"size": "large",
}
}
}).json();
}
Promise.all([getDATA1, getDATA2, getDATA3]).then(values => {
return callback(null, {
DATA1: values[0],
DATA2: values[1],
DATA3: values[2]
})
}).catch(err => {
return callback(err);
});
};

Problem with ottoman not resolving the references

I have two models in my ottoman 1.0.5 setup. One holds contact info which includes an emails array of docs and then the email doc. I can insert new contacts fine as well as emails in docs and the corresponding link in the contact doc for the new email.
Here is my model
const ottoman = require("ottoman")
ottoman.bucket = require("../app").bucket
var ContactModel = ottoman.model("Contact",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
first_name : "string",
last_name : "string",
emails: [
{
ref:"Email"
}
]} )
var EmailModel = ottoman.model("Email",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
type : "string",
address : "string",
name: "string"
} )
module.exports = {
ContactModel : ContactModel,
EmailModel : EmailModel
}
Now to get an contact and all its emails i use this function
app.get("/contacts/:id", function(req, res){
model.ContactModel.getById(req.params.id,{load: ["emails"]}, function(error, contact){
if(error) {
res.status(400).json({ Success: false , Error: error, Message: ""})
}
res.status(200).json({ Success: true , Error: "", Message: "", Data : contact})
})
})
Which returns me this
{
"Success": true,
"Error": "",
"Message": "",
"Data": {
"timestamp": "2019-01-30T23:59:59.188Z",
"emails": [
{
"$ref": "Email",
"$id": "3ec07ba0-aaec-4fd4-a207-c4272cef8d66"
}
],
"_id": "0112f774-4b5d-4b73-b784-60fa9fa2f9ff",
"first_name": "Test",
"last_name": "User"
}
}
if i go and log the contact to my console i get this
OttomanModel(`Contact`, loaded, key:Contact|0112f774-4b5d-4b73-b784-60fa9fa2f9ff, {
timestamp: 2019-01-30T23:59:59.188Z,
emails: [ OttomanModel(`Email`, loaded, key:Email|3ec07ba0-aaec-4fd4-a207-c4272cef8d66, {
timestamp: 2019-01-31T00:36:01.264Z,
_id: '3ec07ba0-aaec-4fd4-a207-c4272cef8d66',
type: 'work',
address: 'test#outlook.com',
name: 'Test Outlook',
}),
OttomanModel(`Email`, loaded, key:Email|93848b71-7696-4ef5-979d-05c19be9d593, {
timestamp: 2019-01-31T04:12:40.603Z,
_id: '93848b71-7696-4ef5-979d-05c19be9d593',
type: 'work',
address: 'newTest#outlook.com',
name: 'Test2 Outlook',
}) ],
_id: '0112f774-4b5d-4b73-b784-60fa9fa2f9ff',
first_name: 'Test',
last_name: 'User',
})
This shows that emails was resolved but why does it not show up in the returned json. On the other hand if i return contact.emails i get the resolved emails just fine. So i hope someone can shed some light on what i am missing here
I asked a similar question on the couchbase forum, and I also found out the solution:
(a slight difference that the result of my search is an array not an object like in your case)
forum.couchbase.com
app.get("/assets", (req, res) => {
AssetModel.find({}, { load: ["assetModelId", "assetGroupId", "assetTypeId"] }, (err, results) => {
if (err) return res.status(400).send("no asset found");
const assets = [];
results.map(asset => {
assets.push({...asset});
});
res.status(200).send(assets)
});
});

Resources