How to display image stored in a variable? - chat

In gifted chat, there is a image field which can be a URL pointing to a image for display. Here is a message example:
{
_id: 30,
createdAt: new Date(),
image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/Paris_-_Eiffelturm_und_Marsfeld2.jpg/280px-Paris_-_Eiffelturm_und_Marsfeld2.jpg',
user: {
_id: 2,
name: 'React Native',
},
},
For a image file stored in a variable img, how can I display it in a chat message? message.image = img did not work.

The following code solves the problem, assuming fileBuffer stores the data stream of the jpeg image file.
{
_id: 30,
createdAt: new Date(),
image: "data:image/png;base64," + fileBuffer,
user: {
_id: 2,
name: 'React Native',
},
},

You can pass the url to source.
Like
<Image
source={{uri: img}}
/>

Related

Getting directly an array from a mongoose model

I'm trying to query directly to an array inside of an mongoose document, but for the moment i have couldn't.
The document example:
{
_id:62141a799b646c7926fcfa9c
firstname:"firstname"
lastname:"lastname"
username:"username"
phone:"0000-0000000"
email:"Example#mail.com"
email_verified_at:null
password:"$2a$10$LUATvtyPmlojHVdCkxP/QO9UUzQgOoGCW6xyx8YPUZkt5l7j6kHxK"
remember_token:null
deleted_at:null
created_at:2022-02-21T23:04:25.097+00:00
updated_at:2022-02-21T23:04:25.097+00:00
notes: [
"621954b8f073154099b92fca"
"62142c426ca950e33baa1302"
]
I have a query that works but i think that isn't the most optimal approach, altough i could be wrong.
I want to get something like this:
[
"621954b8f073154099b92fca"
"62142c426ca950e33baa1302"
]
or populated:
[
{
_id: new ObjectId("621954b8f073154099b92fca"),
user: new ObjectId("62141a799b646c7926fcfa9c"),
type: new ObjectId("62076ce385b4eea8c5aeb8ba"),
title: 'qwasdasd',
content: '',
created_at: 2022-02-25T22:14:16.515Z,
updated_at: 2022-02-25T22:14:16.515Z
},
{
_id: new ObjectId("62142c426ca950e33baa1302"),
user: new ObjectId("62141a799b646c7926fcfa9c"),
type: new ObjectId("62076ce385b4eea8c5aeb8ba"),
title: 'qwasdasd',
content: '',
created_at: 2022-02-25T22:14:16.515Z,
updated_at: 2022-02-25T22:14:16.515Z
}
]
And even if i need to find an specific field, search it, but with the query:
const notes = await collection.findOne({ _id: '62141a799b646c7926fcfa9c', notes: { _id: '621954b8f073154099b92fca' } }, { 'notes.$._id': true });
i have this rersult:
{
_id: new ObjectId("62141a799b646c7926fcfa9c"),
notes: [
"621954b8f073154099b92fca"
]
}
or populated:
{
_id: new ObjectId("62141a799b646c7926fcfa9c"),
notes: [
{
_id: new ObjectId("621954b8f073154099b92fca"),
user: new ObjectId("62141a799b646c7926fcfa9c"),
type: new ObjectId("62076ce385b4eea8c5aeb8ba"),
title: 'qwasdasd',
content: '',
created_at: 2022-02-25T22:14:16.515Z,
updated_at: 2022-02-25T22:14:16.515Z
}
]
}
And i know that i can reach it filtering the ObjectId from user with '-_id notes.$._id' instead of { 'notes.$._id': true } and then destructuring the main object with a const { notes } resulting in this code:
const { notes } = await collection.findOne({ _id: '62141a799b646c7926fcfa9c', notes: { _id: '621954b8f073154099b92fca' } }, '-_id notes.$._id' );
But, it's the best approach to do this? Could i do it in different way being able to take advantage of findOne options like, skip, etc...?
PD: If there's some error it's because it's not the original code, i have modified it because in original code there're many abstractions.
Thanks in advance.

no result with mongoose .find() when looking into array of a single document

I know it's me improperly formatting the query but i cannot seem to get entries in a document from a nested array. What i am attempting to do is retrieve all of the objects in the array with a specific value in the menu field.
I am also using mongo-tenant so the Settings object is already limited to a single document within the collection as it's the only document in settings for that tenant. (req.params.db is referenced earlier in the url than the visible route)
so far i have tried, based on many googlings
.find({}) // returns entire object as below
.find({dropsDowns: { menu: { $eq: req.params.menu }}}) // returns []
.find({ dropsDowns: { menu: req.params.menu } }) // returns []
.find({'dropDowns.menu':req.params.menu}) // returns entire object
.find({ ['dropDowns.menu']: req.params.menu }) // returns entire object
I also tried to do a few forms of the aggregation methods with less than ideal results as that assumes i actually know how to find the right stuff to aggregate, which i obviously do not.
settingsRoute.route('/dropDowns/:menu').get(function(req, res) {
const Settings = baseSettings.byTenant(req.params.db)
Settings.find({}).exec(function(
err,
menu
) {
if (err) {
return res.status(400).json(err)
}
res.status(200).json(menu)
})
})
this returns the below to my browser
[
{
_id: "5cea1b835e13fb4180be2699",
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a3",
menu: "meterIntervals",
text: "250",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a2",
menu: "meterIntervals",
text: "500",
value: 500,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269e",
menu: "transitionIntervals",
text: "Due at normal interval",
value: 0,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be269d",
menu: "transitionIntervals",
text: "Offset by 25% of normal",
value: 250,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
}
],
tenantId: "maxx1",
siteSettings: {
siteTheme: "dark",
friendlyName: "No Name Set :(",
activeStatus: "transit",
previousStatus: "transit",
numBackupsToKeep: 10,
daysPerBackup: 7,
_id: "5cea1b835e13fb4180be26ad",
backups: [ ],
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z"
},
createdAt: "2019-05-26T04:52:19.287Z",
updatedAt: "2019-05-26T04:52:19.287Z",
__v: 0
}
]
What is the proper formatting to only have something like the below return if i were to hit the api with /dropDowns/frequencyOptions
dropDowns: [
{
_id: "5cea1b835e13fb4180be26a7",
menu: "frequencyOptions",
text: "Monthly",
value: 30,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
{
_id: "5cea1b835e13fb4180be26a6",
menu: "frequencyOptions",
text: "Every two months",
value: 60,
tenantId: "maxx1",
createdAt: "2019-05-26T04:52:19.286Z",
updatedAt: "2019-05-26T04:52:19.286Z"
},
}
I am still building the structure of the database so if there is a more efficient way to go about getting this kind of data together then i am open to recommendations as well.
Thanks for any help.
Mongo doc is pretty well done: find()
find method returns a cursor. You need to call .toArray() to turn cursor as a json array.
You may use pagination if there is a lot of result, like with skip/limit.
For the rest model, I would return directly the array of dropDowns, no need to embed it in an object with a dropDowns property.
I ended up just making a new collection just for the dropdown options, the tenant will sort them appropriatly for that page and i can then fo a direct sort with .find({name:req.param.name}) to toArray's needed. Maybe later when i have gained more knowledge about how to handle the returns i will revisit pulling and parsing the array as needed.

What's a good way to look up list of enumerated values?

I have a collection of case with a field named status (integer) whose valid values are 0, 1, 2, 4 and 8, representing "New", "WIP", "Solved", "Canceled" and "Closed" respectively.
So, in mongoose syntax, it might be like:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: Number,
...
});
const statusSchema = new Schema({
value: Number,
description: String
});
Is this a good way to organize the data? How do I make a query to retrieve cases with the status field properly filled with the description?
It is one way to do it sure. You could do the query by using $lookup. It would look something like this:
db.getCollection('<YourCasesColName>').aggregate([
{ $match : { 'status' : 1 } }, // or { $in: [1,2,3] },
{
$lookup: {
from: '<YourStatusColName>',
localField: 'status',
foreignField: 'value',
as: 'statusDoc',
}
}
])
Another way is to add a reference to the actual status via ObjectId so that instead of numbers in the cases you would be storing references to the actual Status objects and in this way have a better referential integrity. However you would still need to do similar query to get both in one shot. So here is what I am talking about:
const caseSchema = new Schema({
createdOn: Date,
subittedBy: String,
status: { type: mongoose.Schema.Types.ObjectId, ref: 'Status' },
// ^ now your status hows reference to exactly the type of status it has
});
const statusSchema = new Schema({
value: Number,
description: String
});
So the actual data would look like this:
// Statuses
[{
_id: <StatusMongoObjectID_1>,
value: 1,
description: 'New'
},{
_id: <StatusMongoObjectID_2>,
value: 2,
description: 'New'
}]
// Cases
[{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_1>
},
{
_id: <MongoObjectID>,
createdOn: '<SomeISODate>',
subittedBy: '<SomeString>',
status: <StatusMongoObjectID_2>
}]

Meteor Mongo adding data to an existing collection

I currently have the the collection "Plans" and it is made upon the creation of a form submit. It inserts the following:
Plans.insert({
location,
address,
date,
time,
notes,
createdAt: new Date(), // current time
owner: Meteor.userId(),
username: Meteor.user().username,
attendees: [
{
attender: [{
user: String,
attending: Boolean,
}],
},
],
});
Then, upon a click of a checkbox, I want a new attender object to be added to the attendees array. So far I have tried to do:
'click .notattending'() {
Plans.insert(
{_id: this._id,
attendees: [{
attender: [
{
user: Meteor.user().username,
attending: false,
}
],
}
]
},
);
},
However it isn't adding to the Mongo collection. Is this the correct way to go about doing it?
You can try this to based on your schema.
Plans.update({ _id: this._id }, {
$push: {
attendees: { user: "", attending: true },
},
});

ExtJS5: Get rid of root property in proxy

I'm trying to connect a REST API to my ExtJS application.
For GET /user alike requests I return a response as follows:
{items: [{id: 1, ...}, {id: 2, ....}], total: 2}
So I created a model for that:
Ext.define('model.User', {
extend: 'Ext.data.Model',
fields: [
{ name: 'id', type: 'int' },
{ name: 'name' },
],
proxy: {
reader: {
type: 'json',
totalProperty: 'total',
rootProperty: 'items'
},
type: 'rest',
url: '/Api/User',
}
});
The grids load data and all look perfect. Now I want to be able to request a single record which my api serves as {id: 1, ...}.
But when I do model.User.load(1) the success handler is never triggered because the response doesn't contain items property. If I put my record in that property, it will work but also will look ugly for other API users.
How can I make it work without the root property? I can't find any events for proxy/reader on a model to change it dynamically.
The rootProperty can also be a function, so you could do something like:
rootProperty: function(raw) {
return raw.items ? raw.items : raw;
}