MongoDB get Value of a Field in NodeJS - javascript

I'm new to MongoDB and I try to create a User Coin System for discord with NodeJS. There is no problem in adding new documents to the collection but i can not access only a single value. I want to return the value of "coins" to let the user see his coins.
I'm using the find() method and it returns a document:
{
"_id": {
"$oid": "5f875963b622f72c3850da6f"
},
"username": "Test",
"userID": "1234",
"messages": {
"$numberInt": "22"
},
"coins": {
"$numberInt": "210"
},
"__v": {
"$numberInt": "0"
}
}
I tried to access "coins" with dot but it always returns undefined:
User.find({userID: message.author.id}).exec((err, res) => {
if (err) return console.log(err);
let embed = new Discord.RichEmbed()
.setTitle(message.author.tag)
.setColor("#4000FF")
.setThumbnail(message.author.displayUserAvatarURL);
//User has no Coins
if(!res){
embed.addField("Coins", "0", true);
return message.reply(embed);
}else {
//res.coins are undefined. Returning 'res' is the whole document from above.
embed.addField("Coins", res.coins , true);
return message.reply(embed);
}
})

1. Try using findOne
2. check your userId in db is string format so it could be a problem .
3. Convert your message.author.id to string before finding. then you will find everything in your result object
let user_id=message.author.id;
User.findOne({userID: user_id.toString()},function(error, body) {
if (error){
result(error, null);
}
var results= body;
})

Related

Async each series not showing proper result, display one element of array instead of all elements

I am newbie to Nodejs and using async.eachSeries to iterate the array, when the array has four elements it only display one element in final response and also add new variable to array called ”payment type”,its not assigning also.
I want to display all elements in array as a final output. Below is the code and is this approach is correct? What I have seen also it first displays all elements in console.log but in postman it shows only one data. How to fix this issue to send all array to postman after the completion of async.eachSeries.
Code:
let members=[];
Utils.async.each(response,(rowTrainers, callback) => {
var result=JSON.parse(JSON.stringify(rowTrainers));
rowTrainers.dataValues.payment_type = "Cashfree";
return callback();
}) ,err=>{
if(err){
console.error("Error: ", err);
cb(err, []);
}else{
members=rowTrainers;
Utils.sendResponse(1, rowTrainers , "success", q)
}
}
Actual Output:
{
"message": [
{
"firstName": “Abc”,
"lastName": "xyzzy”,
“age”:24
}
]
}
Expected Output:
{
"message": [
{
"firstName": “Abc”,
"lastName": “xyzzy”,
“age”:24,
“payment_type”:”Online”
},
{
"firstName": “def”,
"lastName": “pmo”,
“age”:23,
“payment_type”:”Online”
},
{
"firstName": “per”,
"lastName": “abc”,
“age”:23,
“payment_type”:”Online”
}
]
}
Try for the following:
let members=[];
Utils.async.each(response,(rowTrainers, callback) => {
var result=JSON.parse(JSON.stringify(rowTrainers));
rowTrainers.dataValues.payment_type = "Cashfree";
members.push(rowTrainers);
callback();
} ,err=>{
if(err){
console.error("Error: ", err);
cb(err, []);
}else{
Utils.sendResponse(1, members , "success", q)
}
});

Node.js: Cannot read property 'then' of undefined (nested query)

I'm trying to update a field in a MongoDB collection which has nested documents. I have to increase a certain value. The update query works just fine, but I need to nest it in another query where I get the current value, so I could increase it.
The nesting worked just fine when I used a faulty find() method. I realized I must use aggregate(). I can't get it working, the method returns undefined for some reason. I've tried the same aggregate query in the shell and it works, so it has to do something with the Node.js
The function that fails:
static addPointsToUser(mainId, userId, pointsToAdd) {
const db = getDb();
function getCurrent() {
db.collection('mycoll')
.aggregate([
{ $match: { _id: mainId } },
{ $unwind: '$userPoints' },
{ $match: { 'userPoints._id:': userId } },
{ $group: { _id: 'userPoints._id', userPoints: { $push: '$userPoints.points' } } }
])
}
function updateNew(newPoints) {
db.collection('mycoll')
.updateOne(
{ _id: mainId },
{ $set: { "userPoints.$[elem].points": newPoints } },
{
multi: true,
arrayFilters: [{ "elem._id": userId }]
}
)
}
return getCurrent()
.then(result => {
console.log(result);
const newPoints = result.userPoints[0];
return updateNew(newPoints)
.then(result => {
console.log(result);
return result;
})
})
}
The document looks like this:
{
"_id": ObjectId("5d4048f56a895612acabe0a9"),
// Some other fields
"userPoints": [
{ "_id": "manualID1", "points": 80 },
{ "_id": "manualID2", "points": 90 }
]
}
Expected aggregate result:
{ "_id" : "manualID1", "userPoints" : [ 90 ] }
Mongo shell gives the result seen above.
Actual result:
TypeError: Cannot read property 'then' of undefined
If I log the aggregate result it prints and empty array ( [] ).
Your methods getCurrent and updateNew are not returning anything. Which mean you are using .then() on something which is undefined as stated by your error message.
Adding a return statement before db.collection('mycoll') should help you with that.

I want to remove the property inside a object in mongodb

I have this bson doc in a collection. I want to remove a key based on dynamic value.
{
"_id": ObjectId("53ccff9bbb25567911f208a2"),
"image": {
"image1": "5213423424234.jpg",
"image2": "5213423424235.jpg",
"image3": "5213423424236.jpg"
}
}
In request I will get "image1"
temp/5bb3685b663c6f001d14c5da/dl/image1
I saved the key in a variable
let keyid = req.params.k_id
If I call the key directly, this works.
let qry = {
_id: mongojs.ObjectId(req.params.p_id)
}
let update = {
$unset: {
"image.image1": ""
}
}
db.inventory.findAndModify({
query: qry,
update: update,
safe: true
}, function (err, doc) {
if (err) {
res.status(500).json({
"success": false,
"error": err
})
return
}
res.status(200).json({
"success": true,
"message": "Deleted image key"
})
return
})
But since the key is dynamic, I am not able to find the solution with various possibilities
// Try1
$unset: {
'image.' + keyid: ""
},
// Try2
$unset: {
`image.${keyid}`: ""
}
You can try to change the update obj like this
let update = {}
update["$unset"] = {};
update["$unset"]['image.' + keyid] = '';
You need to build up your $unset object programmatically:
This question was answered here: using a variable in mongodb update

javascript undefined, when I just logged it

So I just posted a Q about a nested date object and got a speedy answer, felt kinda silly, it was obvious, but no sooner did I get one correct response when something else throw an undefined error.
I'm inside a method call that "finds" a key, and then I want to use the data in that key for other things
This :
Coupon.findKey( req.params._key, (err, key) => {
if ( err ) {
return res.status(400).send(err);
}
console.log('---------- key '+key+'----------');
});
Gives me this:
---------- key { _id: 5a72c5cbe617796370219fb3, token: 'mWJhRlytyjaxztWfsP6tpH7PccEpSfkemZqyt9pf26e4fI1b32e5Qun8LfLKmkhXMytFtB7QYHHLUgGV0V7AwUB055Cp78Old2IrBHlmgDDFl6qYxe05cgTFLzjmzuAZ', user_id: 5a72c5cbe617796370219fb2, type: 'registration', __v: 0, date: { redeemed: null, issued: 2018-02-01T07:46:19.449Z } }----------
clearly - Coupon.findKey() returned an object. That object "appears" to have _id and user_id available.
However if I do this
Coupon.findKey( req.params._key, (err, key) => {
if ( err ) {
return res.status(400).send(err);
}
console.log('---------- key '+ key._id +'----------');
});
I get
---------- key undefined----------
WHAT THE HECK. Javascript, you break my will...
Help anyone....
And my frustration mounts
mongoose not returning a record
key seems to be an array.
Get the first entry from that array: key[0]._id
key[0] is:
{
"_id": "5a72c5cbe617796370219fb3",
"key": "mWJhRlytyjaxztWfsP6tpH7PccEpSfkemZqyt9pf26e4fI1b32e5Qun8LfLKmkhXMytFtB7QYHHLUgGV0V7AwUB055Cp78Old2IrBHlmgDDFl6qYxe05cgTFLzjmzuAZ",
"user_id": "5a72c5cbe617796370219fb2",
"type": "registration",
"__v": 0,
"date": {
"redeemed": null,
"issued": "2018-02-01T07:46:19.449Z"
}
}

Unable to delete _id field from object after create using feathersjs

i want to modify my hook.data object in my node application after insertion of data. actually i'm not able to.
create: [function(hook, next) {
delete hook.data._id;
hook.data = { problem: hook.data }
postJson(hook.app.get('jsprintUrl'), hook.data)
.then(data =>{
hook.result = data;
next()
})
}]
result: still _id is exist
{
"_id": "59ca334e7bc4e06b140aadf9",
"algorithm": [
{
"name": "SA"
}
]
}
i update object using the hook.result in following way and hook.result will have its Mongoose documents converted to plain objects. more information reference link
create: [function(hook, next) {
delete hook.result._id;
hook.result = { problem: hook.result }
postJson(hook.app.get('jsprintUrl'), hook.result)
.then(data =>{
hook.result = data;
next()
})
}]
result: It was removed from response
{
"algorithm": [
{
"name": "SA"
}
]
}

Categories