How to convert string to int in MongoDB - database

How do i change data of type String to Int in MongoDB. ( Preferably in MongoCompass or Terminal )
I have received a pretty huge dataset with the documents in the following format
To add it to my existing data i need to change the ean from type string to type int.
I already tried the following:
db.products.aggregate([{$project: {ean: { $toInt: "$ean"}}}])
Which gave me the error:
MongoError: Failed to parse number '0002983542515' in $convert with no onError value: Overflow
So i tried the same with convert:
db.products.aggregate([{$project: {_id: 0, result:{ $convert: { input: "ean", to: "int", onError: "An error occured", onNull: "input was null or empty"}}}}])
This is the console.log i got from that:
[ { result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' },
{ result: 'An error occured' } ]
My ean field didn't change, its still from type String.
Any help is highly appreciated
Trying Rakhi Agrawal solution:
but its still a string:

Are you looking for something like this SO post?
You may also find many examples over internet for the same. Below is the snippet from tutorialspoint
db.demo369.insertOne({"Price":"1000000"});
db.demo369.find().forEach( function (d) {
d.Price= parseInt(d.Price);
db.demo369.save(d);
});
Hope I got the question right.

Related

discord.js v14 create channel

I try to create a channel but i always have an error.
I don't find how to fix it.
Don't pay attention to the "req[0]." in "code" it comes from the database, no link with the problem because it works in v13
"It looks like your post is mostly code; please add some more details." I don't know what can I have for more details. haha.
Sorry, English is not my native langage.
error :
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (/root/project/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (/root/project/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:99:14)
at async REST.request (/root/project/node_modules/#discordjs/rest/dist/lib/REST.cjs:52:22)
at async GuildChannelManager.create (/root/new ascension/node_modules/discord.js/src/managers/GuildChannelManager.js:145:18) {
rawError: {
code: 50035,
errors: {
name: {
_errors: [
{
code: 'BASE_TYPE_REQUIRED',
message: 'This field is required'
}
]
}
},
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/guilds/873350117124628552/channels',
requestBody: {
files: undefined,
json: {
name: undefined,
topic: undefined,
type: undefined,
nsfw: undefined,
bitrate: undefined,
user_limit: undefined,
parent_id: undefined,
position: undefined,
permission_overwrites: undefined,
rate_limit_per_user: undefined,
rtc_region: undefined,
video_quality_mode: undefined
}
}
}
Node.js v18.3.0
code :
action.guild.channels.create(`hello`, {
type: "GUILD_TEXT",
parent: cat[0].ID,
permissionOverwrites: [
{
id: bot.user.id,
allow: ['VIEW_CHANNEL', "MANAGE_CHANNELS"]
},
{
id: action.user.id,
allow: ["VIEW_CHANNEL"]
},
{
id: req[0].ID,
deny: ["VIEW_CHANNEL"]
},
{
id: staff[0].ID,
allow: ["VIEW_CHANNEL"]
}
]
})
You can't set the type of the channel using a string anymore, you have to use the new ChannelType enum. You can import it from the discord.js library, and once you've done that, creating a channel would look something like this:
guild.channels.create({
name: "hello",
type: ChannelType.GuildText,
parent: cat[0].ID,
// your permission overwrites or other options here
});
Also make sure that all of your arguments are being passed in only one object, and the name isn't a separate argument.

Find number of occurrences of a certain value in an object - Typescript

I have a nested object and I need to calculate the number of times the 'status' field has a value of 2 and a value of -1. This is what I have.I am open to using lodash as well.
const data = {
"file1": {
"file": {
"path": "file1"
},
"loadedBytes": 1,
"status": 2,
"error": null
},
"file2": {
"file": {
"path": "file2"
},
"loadedBytes": 1,
"status": -1,
"error": "Unexpected error occured - please try again. If error persists, please contact"
},
"file3": {
"file": {
"path": "file3"
},
"loadedBytes": 1,
"status": 2,
"error": null
},
"file4": {
"file": {
"path": "file4"
},
"loadedBytes": 1,
"status": 2,
"error": null
},
"file5": {
"file": {
"path": "file5"
},
"loadedBytes": 1,
"status": -1,
"error": "Unexpected error occured - please try again. If error persists, please contact Trinity"
},
"file6": {
"file": {
"path": "file6"
},
"loadedBytes": 1,
"status": 1,
"error": ""
},
"file7": {
"file": {
"path": "file7"
},
"loadedBytes": 1,
"status": -1,
"error": "Unexpected error occured - please try again. If error persists, please contact Trinity"
},
"file8": {
"file": {
"path": "file8"
},
"loadedBytes": 1,
"status": 1,
"error": ""
},
"file9": {
"file": {
"path": "file9"
},
"loadedBytes": 1,
"status": -1,
"error": "Unexpected error occured - please try again. If error persists, please contact Trinity"
}
}
var countStatus = (status) => Object.values(data).reduce(function(n, i) {
return n + (i.status === status);
}, 0);
console.log({
countSuccess: countStatus(2),
countFailure: countStatus(-1)
})
Is there a better way to achieve the same result? Please note, I am using Typescript and the addition inside the reduce method causes a type error shown here. Please advice.
The error given by TypeScript can be avoided by turning the boolean expression to number explicitly, using the unary plus:
return n + +(i.status === status);
For the rest your solution is fine.
You can use _.countBy() to get an object with the counts of all statuses, and then get the ones you want by destructuring the object (stackblitz):
const data = {"file1":{"file":{"path":"file1"},"loadedBytes":1,"status":2,"error":null},"file2":{"file":{"path":"file2"},"loadedBytes":1,"status":-1,"error":"Unexpected error occured - please try again. If error persists, please contact"},"file3":{"file":{"path":"file3"},"loadedBytes":1,"status":2,"error":null},"file4":{"file":{"path":"file4"},"loadedBytes":1,"status":2,"error":null},"file5":{"file":{"path":"file5"},"loadedBytes":1,"status":-1,"error":"Unexpected error occured - please try again. If error persists, please contact Trinity"},"file6":{"file":{"path":"file6"},"loadedBytes":1,"status":1,"error":""},"file7":{"file":{"path":"file7"},"loadedBytes":1,"status":-1,"error":"Unexpected error occured - please try again. If error persists, please contact Trinity"},"file8":{"file":{"path":"file8"},"loadedBytes":1,"status":1,"error":""},"file9":{"file":{"path":"file9"},"loadedBytes":1,"status":-1,"error":"Unexpected error occured - please try again. If error persists, please contact Trinity"}}
const { '2': countSuccess, '-1': countFailure } = _.countBy(data, 'status')
console.log({ countSuccess, countFailure })
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

Why mongoose ignores "commentId" property in document.comments array?

I have a some code:
const taskId: number = req.body.taskId;
const text: string = req.body.text;
const task = await db.tasks.findOneAndUpdate(
{ taskId },
{ $push: { comments: [{
commentId: await db.getId(`task.${taskId}.commentId`),
taskId,
// #ts-ignore
author: Number(req.session.userId),
text,
timestamp: Date.now()
}] } }
).catch(e => {
console.error(e);
return res.status(400).json({ errors: [{ msg: "UNKNOWN_ERROR" }] });
});
if (!task) return res.json({ errors: [{ location: "query", msg: "NOT_FOUND", param: "taskId" }] });
return res.json(task);
But I have out (I skipped other properties):
{
...,
comments: [{
"timestamp": 1595833609905,
"_id": "5f1e7d09c1e15d4c8e0b71fa",
"taskId": 2,
"author": 435214391,
"text": "haha test comment"
}]
}
In comment property "commentId" is undefined.. But if I use
console.log({
commentId: await db.getId(`task.${taskId}.commentId`),
taskId,
// #ts-ignore
author: Number(req.session.userId),
text,
timestamp: Date.now()
})
I see the "commentId" property. Why it not saves in database? (Mongoose)
Okey, this is win. Error has been found in imports:
import TaskResponseSchema from './TaskResponse';
import TaskCommentSchema from './TaskResponse';
But okey:
import TaskResponseSchema from './TaskResponse';
import TaskCommentSchema from './TaskComment';

Mongoose Schema: Not able to save sub document

I am trying to save document in mongodb. Don't have any success.
JSON:
{
"ticketType": "Enquiry",
"type": "AA",
"subType": "BB",
"subSubType": "CC",
"misidnProfile": {
"serviceTypes": [
"Postpaid", "Prepaid"
],
"circles": [
"AA", "BB"
]
}
}
Mongoose Model :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var misidnProfile = new Schema({
serviceTypes: [String],
circles: [String],
});
var taggingProfile = new Schema({
ticketType: {type:String, required: true},
type: {type:String, required: true},
subType: {type:String, required: true},
subSubType: {type:String, required: true},
misidnProfile: {misidnProfile},
});
module.exports = mongoose.model("TaggingProfile", taggingProfile);
Code for saving data:
module.exports.createTaggingProfile = function(req, res){
var taggingProfile = new TaggingProfile(req.body);
taggingProfile.save(function (err, tg) {
if(err){
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Saved TaggingProfile',
obj: tg
});
});
};
It is saving taggingProfile but not subdocument msisdnProfile. I am not able to understand where is the problem?
EDIT:
Now it is saving. Thanks #Neil
While updating document, I am sending JSON as
{
"ticketType": "Enquiry",
"type": "AA",
"subType": "BB",
"subSubType": "CC",
"misidnProfile": {
"serviceTypes": [
"Postpaid", "Prepaid", "ABC","PQR"
],
"circles": [
"AA", "BB"
]
}
}
Strange thing is observed that when i am trying to find document by id, I am getting TaggingProfile object, But it don't have msisdnProfile value.
Check below code.
TaggingProfile.findById(req.params.id, function (err, tg) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!tg) {
return res.status(500).json({
title: 'No TaggingProfile Found!',
error: {message: 'Message not found'}
});
}
req.taggingProfile=tg;
if(tg.misidnProfile){
console.log("## tg.misidnProfile PRofile present");
} else {
console.log("## tg.misidnProfile Not present");
}
for(var p in req.body){
req.taggingProfile[p] = req.body[p];
}
req.taggingProfile.save(function (err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Updated message',
obj: result
});
});
});

Meteor $push multipoint array

I set coordinates in a geolocation array:
Crowds.insert({
location: {"type": "MultiPoint","coordinates":
[[1, 1]]
}
});
Crowds._ensureIndex({ location: "2dsphere" });
Then I try to add value. To do so I make a §push to add new value in "coordinates" array:
Crowds.update(
{ _id: crowd[0]._id },
{ $push: { location: { "coordinates": [ 2, 2 ]
}}}
);
I get the folling error:
Exception in Mongo write: TypeError: object is not a function
It seems that I am not updating coordinates array the proper way... I tried various combinations but cannot find how to add value in a nested array...
Please help ;) Thanks
Is there a typo there?
crowd[0]._id
"crowd" is singular there, yet you're calling [0] as if it's an array.
Should it be:
crowds[0]._id
I think I found the problem, and actually I didn't ask the question well... sorry
The following code returned error:
Crowds.update(
{ _id: '123' },
{ $inc: { people: 1 } },
{ $push: { "location.coordinates": [ Meteor.user().profile.location.coords.longitude, Meteor.user().profile.location.coords.latitude ],
{ $set: { modified: new Date().valueOf() } },
function(error){
return "Update error: " + error;
}
);
But it works with:
Crowds.update(
{ _id: '123' },
{ $inc: { people: 1 } },
{ $set: { modified: new Date().valueOf() } },
function(error){
return "Update error: " + error;
}
);
Crowds.update(
{ _id: crowd[0]._id },
{ $push: { "location.coordinates": [ Meteor.user().profile.location.coords.longitude, Meteor.user().profile.location.coords.latitude ]
}},
function(error){
return "Update error: " + error;
}
);
It seems that $push needs to be used alone, tell me if I am wrong in diagnostic ;)

Resources