save images mongodb node js - node.js

schema
images:{ type : Array , "default" : [] }
controller
return new Promise(function(resolve,reject){
var dt = new Date(req.body.dateOfBirth)
var experiences = new Experiences({
'images': req.body.images
});
experiences.save(function(err,experiences){
if(err){
reject(err);
}else{
resolve(experiences);
}
});
});
I need to save more than one image into single image
posting Data as :
"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb","https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb"
but when i viewing my document. getting result like this :
"images" : [
"\"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb\",\"https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb\""
]
what am i doing wrong please help?
i want result like:
"images" : [
"https://images.pexels.com/photos/346768/pexels-photo-346768.jpeg?w=940&h=650&auto=compress&cs=tinysrgb","https://images.pexels.com/photos/287240/pexels-photo-287240.jpeg?w=940&h=650&auto=compress&cs=tinysrgb"
]

My guess is that req.body.images is stringified. I believe it is a string containing many values, not an array. When you post that to MongoDB, since you specified that images must be an array, it saves it as an array of strigified values.
So, blind guess, but I believe you are posting (client-side) something like :
$.post("/save", { images : JSON.stringify(imagesArray) } )
when you should just post your array as is :
$.post("/save", { images : imagesArray} )
But it's hard to know for sure, because we don't have the front-end code or even console.log(req.body.images)

Related

How to get particular fields in array of objects mongodb

I need only path in every object in the above showing figure.
I tried something like this
userRouter.post('/delete_products',function(req,res){
Collections.product.find({ "_id": req.body.id }, { "pimages.path": "1" },function(err,result){
if(err)
res.send(err)
else
res.send(result)
const map=result.map(user=>user.pimages.map(user=>user.path))
console.log(map);
})
})
[ [ '1552640783_mixer front.jpg', '1552640783_mixer back.jpg' ] ]
I am getting like this. I am expecting output in array of object form
[{'1552640783_mixer front.jpg'},{......}]
Thanks in advance.
In Object the values are written as name : value pairs.
Ex:
{
name : "M-DIT KOZHIKODE",
location : "Kerala",
established : 2012
}
I didn't get the logic behind your expecting result.

Dynamic URL with mongo method

Regarding these post : Mongoose prototype : how to insert an url dynamically?
I'm looking to do pretty much the same (URI dynamically insert).
The solution provided is good but I do not understand some things...
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PicturesSchema = new Schema({
album : { type : String, required : true, trim : true },
pictures : { type : Array, required : false, trim : true }
});
PicturesSchema.virtual('pictureUrls').get(function() {
return this.pictures.map(function(picture) {
return 'https://s3.amazonaws.com/xxxxx/'+ picture;
});
});
var Pictures = mongoose.model('Pictures', PicturesSchema);
// Demo:
var pictures = new Pictures({
album : 'album1',
pictures : [
'1434536659272.jpg',
'1434536656464.jpg',
'1434535467767.jpg'
]
});
console.log( pictures.getPics() );
The given solution injects a "virtual field" in addition to retaining the "pictures" field with the name of the images (without URL).
How to retain only the field "PicturesURL" containing the full URL of the image without displaying a redundancy with the "Pictures" field?
How to retrieve and display the JSON format query results as it knowing that data.ToJson returns an error: has no method 'toJson'?
Pictures.find().exec(function(err, data){
if(err){
console.log(err);
}
console.log('%j', data.toJSON({ virtuals : true }) );
});
A strategy to store only the picture url without the picture would be to create a Mongoose middleware on save.
You could then populate the picture field with the name of the picture, and the full url will be the one stored in the database and later retrieved.
For example:
PictureSchema.pre('save', function (next){
if (this.isModified(pictureUrls){
this.pictureUrls = this.pictureUrls.map(function(picture){
return 'https://s3.amazonaws.com/xxxxx/'+ picture;
})
}
});
With this solution, every time you modify the pictures array, it will go over every element of the array and add the s3 path.
Since it won't be a virtual, it will be easier for you to use the model with event using toObject or toJson.

mongoose-encryption and updating objects

I know the mongoose-encryption doc states:
update will work fine on unencrypted and unauthenticated fields, but will not work correctly if encrypted or authenticated fields are involved.
And I've observed that when I use the mongoose create method that my fields are encrypted into the _ct field. However if I then use findByIdAndUpdate to update my object I see the fields are created in plain text (as output from mongodb console via find command).
From save
> db.tenants.find().pretty()
{
"_id" : ObjectId("554b7f8e7806c204e0c7589e"),
"_ac" : BinData(0,"YdJjOUJhzDWuDE5oBU4SH33O4qM2hbotQTsF6NzDnx4hWyJfaWQiLCJfY3QiXQ=="),
"_ct" : BinData(0,"YaU4z/UY3djGCKBcgMaNIFHeNp8NJ9Woyh9ahff0hRas4WD80V80JE2B8tRLUs0Qd9B7IIzHsq6O4pYub5VKJ1PIQA+/dbStZpOH/KfvPoDC6DzR5JdoAu+feU7HyFnFCMY81RZeJF5BKJylhY1+mG4="),
"__v" : 0
}
After findByIdAndUpdate
> db.tenants.find().pretty()
{
"_id" : ObjectId("554b7f8e7806c204e0c7589e"),
"_ac" : BinData(0,"YdJjOUJhzDWuDE5oBU4SH33O4qM2hbotQTsF6NzDnx4hWyJfaWQiLCJfY3QiXQ=="),
"_ct" : BinData(0,"YaU4z/UY3djGCKBcgMaNIFHeNp8NJ9Woyh9ahff0hRas4WD80V80JE2B8tRLUs0Qd9B7IIzHsq6O4pYub5VKJ1PIQA+/dbStZpOH/KfvPoDC6DzR5JdoAu+feU7HyFnFCMY81RZeJF5BKJylhY1+mG4="),
"__v" : 0,
"userId" : ObjectId("55268f43cbfc87be221cd611"),
"social" : "123-45-6789",
"last" : "bar",
"first" : "foo"
}
Is there a recommended strategy for updating objects and maintaining the encryption with mongoose-encryption?
As you quoted, the documentation for mongoose-encryption clearly tells that it does not work for update.
https://github.com/joegoldbeck/mongoose-encryption
Mongoose update hook is little tricky as well.
What you can do potentially is model your collection in such a way that fields which needs to be encrypted are a separate collection altogether and in the paren collection just link them via ids.
Person = {
_id: <ObjectId>
name: Blah
..
..
documents: [
{ 'doc_id': <ObjectId1> },
{ 'doc_id': <ObjectId2> },
]
}
Documents = [
{
"_id" : <ObjectId1>,
"_ac" : BinData(0,"YdJjOUJhzDWuDE5oBU4SH33O4qM2hbotQTsF6NzDnx4hWyJfaWQiLCJfY3QiXQ=="),
"_ct" : BinData(0,"YaU4z/UY3djGCKBcgMaNIFHeNp8NJ9Woyh9ahff0hRas4WD80V80JE2B8tRLUs0Qd9B7IIzHsq6O4pYub5VKJ1PIQA+/dbStZpOH/KfvPoDC6DzR5JdoAu+feU7HyFnFCMY81RZeJF5BKJylhY1+mG4="),
"__v" : 0
}
...
...
]
This will increase code reuse as well.
I have implemented an strategy that i don´t think it is most efficient but it works.
I need to have all my data in database encrypted so i can´t use the above approach.
What i did is to create an update function that finds the document i want to modify, then i construct a new schema object and assing the _id of the found document to the new object.
Then i delete the original document and after that save the new object wich has the original _id. The only problem i found is that mongoose throw an error because duplicated _id that is printed in the console but it still works and _id aren´t duplicated.
I have tried replacing the_id and traking the document with another property but it still throw that error, anyway data is stored as expected.
exports.update= (req, res, next) => {
Solucion.findOne({_id: req.params.id})
.then(document => {
if (!document) {
res.status(404).json({
message: notFoundMessage,
data: null,
error: null
})
} else {
const solucion = new Solucion({
_id: document._id,
identificacion: document.identificacion,
informacion: document.informacion,
estado: req.body
})
Solucion.deleteOne({_id: document._id})
.then(() => {return solucion.save()})
.then(result=> {
return res.status(201).json({
message: editedSavedMessage,
data: result,
error: null
});
})
.catch(err => {
errorHandler.errorHandler(err, res);
})
}
})
};
UPDATE 29/07/2020
I have found that if you use the save method using the same _id, data is stored encrypted but Mongo creates your schema structure but with all values set to null.
Beyond that it seems to work as expected as data is not visible in DB.

Migrating using mongify

I'm using mongify to migrate a mysql database into mongodb.
Doing that, 2 questions appeared:
1- How can i declare my translation file in order to have a embedded array of ids that references to the objects (that are stored in a different collection and can be retrieved through populate), instead of just embedding as json objects.
2- Embedded objects can have an unique id as objects in colections do?. On other projects i've used that approach to query for embedded objects, but if that id is not present i should use a different field.
Unfortunately the first request isn't possible with Mongify at the moment, it requires a custom script to do that.
I could give you more details if you want to send me your translation file (Make sure to remove any sensitive data).
As for number two, the embedded object will get a unique ID. You don't need to do anything special.
Hope that answers your questions.
from mongify isn't possible but in mongodb you can transform data as follows:
//find posts has array of objects
db.getCollection('posts').find({'_tags.0': {$exists: true}}).forEach( function (post) {
var items = [];
var property = '_tags';
post[property].forEach(function(element){
if(element._id !== undefined){
items.push(element._id);
}
});
if(items.length>0){
post[property] = items;
db.posts.update({_id:post._id},post);
}
});
Source Document:
{
"_id" : ObjectId("576aa0389863482f64051c81"),
"id_post" : 130155,
"_tags" : [
{
"_id" : ObjectId("576a9efd9863482f64000044")
},
{
"_id" : ObjectId("576a9efd9863482f6400004b")
},
{
"_id" : ObjectId("576a9efd9863482f64000052")
},
{
"_id" : ObjectId("576a9efd9863482f6400005a")
}
]
}
Final Document:
{
"_id" : ObjectId("576aa0389863482f64051c81"),
"id_post" : 130155,
"_tags" : [
ObjectId("576a9efd9863482f64000044"),
ObjectId("576a9efd9863482f6400004b"),
ObjectId("576a9efd9863482f64000052"),
ObjectId("576a9efd9863482f6400005a")
]
}

Nodejs,mongodb - using $nin or $in for object ids or _id

I am using Nodejs, mongodb database. We can use $nin like this
Model.find({ uname : { $nin : ["sachin","saurav"] } }....
above words for normals elements like uname and others. But for object ids(_id), ..
Model.find({_id : {$nin : ["6534767457dfgbyb23","wtvwt3wy5etvdh"] } } ...
above line not giving error, it is showing correctly..
var ObjectID = require('mongodb').ObjectID;
var a = new ObjectID("sdfsdznfsdz");
var b=new ObjectID("sdfjwneufhq2rfwefsd");
Model.find({_id : { $nin : [a,b] } }...
above also not giving error...
The problem is, I cant write manually like a,b,c,d...
I have to store all those a,b,c,d... in some variable in some correct format, and have to do like this
Model.find({_id : {$nin : variable } }
or
Model.find({_id : {$nin : [variable] } }
I tried this
var string = a+","+b //this didnt work, error : invalid object id
var string = "nfw34qfhrs9"+","+"u89tgngnfdb" //this also same error
var string = "\"jn4tr43r\"" + "," + "\"ansfuw37fe\"" //this also same error
What should I do? the thing is, I should get all items except those items with those _ids.
The way $nin works in mongo is that it takes an array of values to check.
The code:
var string = a+","+b Doesnt make this a valid array. as you're creating a string with the value sdfsdznfsdz, u89tgngnfdb
So $nin is treating the array as that value, not the way you're trying to implement.
Solution to do what you want is to create an array with those values.
So something like:
var ids = new Array( new ObjectId("1124edcef241"), new ObjectId("56943decfeca845") );
// Dont put [ ] as a parameter. Just send a variable thats an array
Model.find( {_id : { $nin : ids } } );
...
Just incase you're a tad hazy regarding arrays, I suggest having a read of this:
http://www.w3schools.com/js/js_obj_array.asp
Not able to comment yet, but just wanted to add here that new ObjectID() wasn't working for me, but new ObjectId() (lowercase d) did work. Hope this helps someone.

Resources