set model values from json in nodejs - json

Hi Guys I want to know how to save json string into mongoose model object?
let me explain a simplified version of my problem:
I have a schema model:
const mongo = require('mongoose');
const clientSchema = mongo.Schema({
name: {type: String},
age: {type: Number},
updated_at: {type: Date},
}
and I have a put method which is shown below:
var Client = mongo.model('client', clientSchema);
//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
Client.model.findById(req.params._id, (err, foundedclient) =>
{
if(err) res.send(err);
//***********************************************************//
/*I want to update foundedclient from req.body here! */
/*some function like : foundedclient.JsonTovalues(req.body); */
//***********************************************************//
foundedclient.updated_at = new Date().toISOString();
foundedclient.save((err) =>
{
res.send('saved successfully!');
});
});
});
the req.body is a json:
{
"name":"bardia",
"age":27,
}
I want to update foundedclient value from req.body at the position I highlighted in the code by //*******// signs. I want a hypothetical function such as foundedclient.JsonTovalues(req.body). what is the best way to achieve that? In other words what is the best way to save json as mode values?
Thank a lot

you can define an instance method to something similar to updateByJson as explained below
const clientSchema = mongo.Schema({
name: {type: String},
age: {type: Number},
updated_at: {type: Date},
}
// here simply calling update method internally but exposed as an instance method
clientSchema.methods.updateByJson = function(jsonToUpdate, cb){
// will work if you are using mongoose old version 3.x
this.constructor.update({_id: this._id}, {$set:jsonToUpdate}, cb);
// should work with latest versions
this.model('client').update({_id: this._id}, {$set:jsonToUpdate}, cb);
}
Your client code will look like this
var Client = mongo.model('client', clientSchema);
//Update User
server.put(`/api/clients/:_id`, (req, res) =>
{
Client.model.findById(req.params._id, (err, foundedclient) =>
{
if(err) res.send(err);
jsonToUpdate = req.body
jsonToUpdate.updated_at = new Date().toISOString();
foundedclient.updateByJson(jsonToUpdate, (err) => {
res.send('saved successfully!');
});
});
});
I hope this helps you.

Related

How to convert MySql Buffer to Image in React/Node/Express

I need help to convert a buffer to a base64 using Node and React.
I'm posting an image with an input to my databse and I'm not sure I'm doing it right. This is my first time doing this. Is there something missing here? Back-end POST request:
app.post("/api/img", (req, res) => {
const productimg = req.body.productimg;
const sqlInsert = "INSERT INTO users_files (file_src) VALUES (?)";
db.query(sqlInsert, [productimg], (err, result) => {
console.log(result);
})
})
In the database the image is a blob, and then with the GET request I get the image as a buffer. This is the GET request in the front-end:
useEffect(() => {
Axios.get('http://localhost:3001/api/get/img').then((base64String) => {
setBackenddata(base64String.data)
var blob = new Blob(productImg[0]?.file_src, {
type: "image/jpg",
});
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
let base64String = reader.result;
setProductImg(base64String);
};
console.log(base64String)
})
}, [])
And this is the get function in the back-end:
app.get('/api/get/img', (req, res) => {
const sqlGet = "SELECT * FROM users_files";
db.query(sqlGet, (err, result) => {
res.send(result);
})
})
This is what I get from the base64String:
The base64String does not seem to do anything, since it is still type: buffer.
In the back end I have tried with a Multer, but that did not work. I've been trying with different things in the back-end and the front-end, but since I'm new to this it is hard to know what's wrong.

findOneAndUpdate in mongoose (MERN)

A small bottleneck arose while developing a short tutorial:
I would like to be able to push this model:
const studentFatherSchema = new Schema ({
yam:{
type: String,
trim: true
},
emailmanagement: {
type: String,
trim: true
},
students: [{
name: {
type: String,
trim: true
}
}]
});
Would I first have to find the parent object with findById (req.params.studentFatherId) and then do the update, or can I do it all at once? I'm trying to do it all at once, but I can't, what do you recommend?
Note: I can update the name and emailmanagement fields without problems, but doing an update with the push does not add it to me, I am testing it with Postman and
I have something like this but it doesn't work!
exports.updateAddChild = async (req, res, next) => {
try {
const student = req.body;
const studentFather = await StudentFather.findOneAndUpdate (
{_id: req.params.studentFatherId},
{$ push: {students: student}},
);
} catch (error) {
console.log (error);
next ();
}
}
Thank you very much for your help!

Getting JSON object out of Function in nodejs

I am currently trying to get a JSON object out of a function.
I can access all the data in the function, but I am struggling to get the data out so I can actually use the Data.
var imdb = require('imdb');
imdb('tt4477536', function(err, data) {
if(err)
console.log(err.stack);
if(data)
console.log(data)
});
This works fine and I get the Data:
{ title: 'Fifty Shades Freed',
year: '2018',
contentRating: 'R',
runtime: '1h 45min',
description: 'Anastasia and Christian get married, but Jack Hyde
continues to threaten their relationship.',
rating: '4.4',
poster: 'https://images-na.ssl-images-amazon.com/images/M/MV5BODI2ZmM5MzMtOWZiMC00ZGE3LTk3MWEtY2U0ZjE3ZWJlNDEzXkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_UX182_CR0,0,182,268_AL_.jpg',
genre: [ 'Drama', ' Romance', ' Thriller' ],
director: 'James Foley',
metascore: '31',
writer: 'Niall Leonard' }
So now my question is how do I get the Data out of this function, so I can actually use the data somewhere else in the code? like if i need the title in a string?
thanking you in advance.
Thomas
You can just declare a variable outside it:
var imdb = require('imdb');
var imdbData = {};
imdb('tt4477536', function(err, data) {
if(err)
console.log(err.stack);
if(data) {
imdbData = data;
console.log(data);
}
});
But do mind that since this is an asynchronous function you should be using a callback or Promise to be safe when using tha data. For a better approach:
var imdb = require('imdb');
imdb('tt4477536', function(err, data) {
if(err)
console.log(err.stack);
if(data) {
doNext(data);
}
});
function doNext(data) {
//use the data
}

Updating sub array in JSON with a REST API in Mean Stack

I'm developing a MEAN stack application and I'm hung up on how to actually update a document that has been saved into the MongoDB already. I've seen that I have to use patch instead of post in my REST API paths, but it's still a little clouded to me. I want to insert a new Package into the Package JSON Array in the User JSON.
Possible Duplicate, but he's overriding a value in the array and not adding a new object into it.
My JSON Schema:
//User schema
const UserSchema = mongoose.Schema({
name: {
type: String
},
email: {
type: String,
require: true
},
username:{
type:String,
required: true
},
password:{
type:String,
required: true
},
packages: [{
from: String,
to: String,
tracking: String
}]
});
My REST API Paths
//Update
router.patch('/update', (req, res) => {
const username = req.body.username;
const packages = req.body.packages;
User.getUserByUsername(username, (err, user) => {
if(!user){
return res.json({success: false, msg: 'User not found'});
} else {
User.addPackages(user, req.body.packages, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to update packages'});
} else {
res.json({success: true, msg:'update packages'});
}
})
}
});
});
My Module's:
module.exports.addPackages = function(user, packages, callback){
User.findOneAndUpdate(
{username:user.username},
{$push: {"packages" : {
"to" : packages.to,
"from" : packages.from,
"tracking" : packages.tracking
}}},
{new:true},
function(err, newPackage){
if (err) throw err;
});
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}
They're updating into my MongoDB, but just the object ID and not the values...
db.your_collection.update({},
{$set : {"new_field":1}},
{upsert:false,
multi:true})

Sailjs-Waterline: Serialize, Parse and initialize an Model

Let's assume that I found user using next command:
User.findOne(id).exec(function(err, user){
redis.set(JSON.stringify(user), id);
})
After that I'm loading from redis my object
redis.get(id, function(err, reply){
if(!err && reply) {
var user = JSON.parse(reply);
// here methods like user.save() or any of defined manually by developer is unavailable
//
} else {
..
}
})
User model example:
module.exports = {
attributes : {
// Simple attribute:
// name: 'STRING',
// Or for more flexibility:
// phoneNumber: {
// type: 'STRING',
// defaultValue: '555-555-5555'
// }
email : {
type: 'string',
unique: true
},
// ...
verifyPass: function(pass, callback) {
var obj = this.toObject();
if (callback) {
return Password.compare(pass, obj.local.password, callback);
}
return Password.compareSync(pass, obj.local.password);
},
// retrieve profile for sending to front end
getProfile: function() {
var obj = this.toObject();
var profile = {};
profile.id = obj.id;
// ...
return profile;
},
I need all of that methods to be work whenever I parse waterline model from json. Is there a way to initialize it without triggering db at all. Also would be nice if I could to call user.save().
There's currently no documented public API for this unfortunately, but you can use,
var user = new PersonCollection._model(values, {showJoins: true});
See how that works for you!