how to get key value from json result in node js - javascript

how can I get specify email and its value only, from JSON array result which should be like=>only( email: abc#gmail.com)
here is my code:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
this is the result which i am getting in console
[ { _id: 5a9f8849fc49ca1ff4aee3dc,
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' } ]

This is a simple JavaScript:
var res = [
{ _id: '5a9f8849fc49ca1ff4aee3dc',
email: 'abc#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3dd',
email: 'abcd#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' },
{ _id: '5a9f8849fc49ca1ff4aee3de',
email: 'abcde#gmail.com',
bid_amount: '200',
bid_time: '22:22:22:22',
bid_location: 'abbottabad',
bid_status: 'false' }
];
var finalRes = res.map(({email}) => ({email}));
console.log(finalRes);

You can use reduce or map on your array:
Using reduce
reducedResults = result.reduce((accumulator, current) => {
accumulator.push({ email: current.email });
return accumulator;
}, [])
Using map
mappedResults = result.map((user) => {
return { email: user.email };
})

You could use select method from mongoose api. Basically, you can control with it what will result object contains of its properties. So, your code could look like this:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Scream_It");
var query = { bid_location : 'abbottabad' };
dbo.collection("bid_placement").find(query).select({email: 1, _id: 0}).sort({bid_amount:-1}).limit(1).toArray(function(err, result){
if (err) throw err;
console.log(result);
// console.log(JSON.stringify(result));
var string = JSON.stringify(result);
console.log(string);
var objectValue = JSON.parse(string);
// console.log(objectValue);
console.log(objectValue.email);
You should get something like this:
[ { email: 'abc#gmail.com'} ]
If you need _id, use this in select {email: 1, _id: 1}

Related

How to retrieve value from another mongoose collection

I'm attempting to find() in one collection and concatenate that value to the correct object returned by subsequent find(). However I cannot guarantee the value retrieved in the first find() will match the index . How do I ensure the first value (Boolean) is attached to the correct instance of the second find()?
What I have so far is to use the indexes of the first condition but it may not match if an instance has been removed
My Model:
let Instance= new Schema({
imgName: String,
offer: String,
brand: String,
desc: String,
keywords: Array,
loc: String,
location: {
type: {
type: String, // Don't do `{ location: { type: String } }`
enum: ['Point'], // 'location.type' must be 'Point'
required: true
},
coordinates: {
type: [Number],
required: true
}
},
categories: Array,
userId: String,
active: Boolean,
stockPic: String,
startTime: Number,
endTime: Number,
range: Boolean
});
mongoose.model('Beams2', Instance);
let LikesSchema = new Schema({
userId: String,
likeId: String,
categories: Array,
public: Boolean
});
mongoose.model('Likes', LikesSchema);
//My query:
exports.findAllLikes = function(req, res){
Likes.find({'userId': req.body.userId}, function(err, results) {
let likeIds = results.map((currentValue, index, array) => {
return currentValue.likeId;
});
let statusArr = results.map((currentValue, index, array) => {
return currentValue.public;
});
Instances.find({'_id': { $in: likeIds }}, function(err, favs){
if (err) return console.log(err);
let newArr = [];
favs.forEach(function(element, i) {
//console.log(statusArr[i]);
let post = element.toObject();
post.public = statusArr[i]; //need to guarantee correct value
newArr.push(post);
console.log(post);
});
return res.send(newArr);
});
});
};
I think, this is how you could achieve what you are looking for:
exports.findAllLikes = function(req, res) {
Likes.find({
'userId': req.body.userId
}, (err, results) => {
if (err) {
console.log('Error while fetching likes: ', err);
return res.status(500).json({
Error: 'Error while fetching likes.'
});
}
const likeIds = results.map(({
likeId
}) => likeId);
Instances.find({
'_id': {
$in: likeIds
}
}, (err, favs) => {
if (err) {
console.log('Error while fetching likes: ', err);
return res.status(500).json({
Error: 'Error while fetching Instances.'
});
}
let newArr = [];
favs.forEach((elem) => {
let post = elem.toObject();
const likeDoc = results.find(({
likeId
}) => likeId === post._id.toString());
post.public = (likeDoc && likeDoc.public) ? likeDoc.public : '';
newArr.push(post);
});
console.log(post);
return res.status(200).send(newArr);
});
});
};
You shouldn't ever play with indexes for mapping stuff, until and unless you are sure that you have same length arrays.
Hope this helps :)

convert rowdatapacket into array , How to convert mysql node.js api rowdatapacket to array , string to array

please help me to convert my rowdatapacket into array of array or nested array
enter code here
router.get('/getPosts/:user_id', (req, res, next) => {
connection.query('SELECT * FROM files WHERE user_id = ?', [req.params.user_id], (err, rows, fields) => {
if (!err) {
resultArray = JSON.parse(JSON.stringify(rows));
console.log(resultArray);
return res.status(200).send(resultArray);
} else {
console.log(err);
return res.status(404).send('Sorry user_id does not exits');
}
})
});
OUTPUT
OutPut:
{ post_id: 17,
user_id: 1,
description: ' Hi How are you ',
file_name: 'iron_man_5k_2.jpg,iron_man_captain.jpg',
mimetype: 'image/jpeg,image/jpeg',
size: '5696459,180',
saved_name:
'1546438737564_iron_man_5k_2.jpg,1546438737672_iron_man_captain.jpg',
file_path:
'uploads1546438737564_iron_man_5k_2.jpg,uploads1546438737672_iron_man_captain.jpg',
created: '2019-01-02T14:18:57.000Z' }

mongoose find json inside layers json

queueModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var queueSchema = Schema({
title: String,
description: String,
abc:{
a1: String,
b1: String,
c1: String
},
});
var Queue = mongoose.model('Queue', queueSchema);
module.exports = Queue;
api1.js
Queue.findOne({ title: "zzzz"} ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
result is data ...
api2.js (problem)
Queue.findOne({ title: "zzzz", abc:{a1: "aaaa"} } ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
Why is it null?
I want to use a1 condition.
Ask a Solution.
Do not modify the schema.
Try this:
Queue.findOne({ title: "zzzz", "abc.a1": "aaaa"} } ).exec((err, data) => {
if (err) console.log(err)
else console.log(data)
});
To filter on the abc you need to do abc.a1 as the field.

node.js - How to return an ObjectId by name in Mongoose

I have this code for setting an ObjectID to brand property of an productSchema:
productSchema.path('brand').set(function (namebrand) {
var brandID;
Brand.findOne({ 'name': namebrand }, 'id name', function (err, result){
if (err) console.log(err);
if (result){
// console.log("Result: "+result);
brandID = result.id;
} else {
var newBrand = new Brand({name:namebrand});
newBrand.save(function (err, newBrandID){
console.log("newBrandID : "+newBrandID)
brandID = newBrandID.id;
});
}
});
return mongoose.Types.ObjectId(brandID);
});
My problem is when the Brand ObjectID setter executes, I got differents ObjectId's
for example:
return mongoose.Types.ObjectId(brandID); // 52ffaa218050b7c4652502de
console.log("newBrandID : "+newBrandID) // newBrandID : { __v: 0, name: 'new Brand name', _id: 52ffaa218050b7c4652502df }
So what is the correct way to do what I want? I'm a newbie on this :/
P.S.: Thanks in advance, and sorry for my English.
You can't use a return value here. A mongoose set needs to be synchronous and you are making a DB query which is asynchronous. Look up the brand in the DB first, then set it on the product.
var productModel; // you must already have loaded this
var namebrand = "somebrand";
Brand.findOne({ 'name': namebrand }, 'id name', function (err, result){
if (error) {
console.error(error);
return;
}
if (result){
productModel.brand = result._id;
} else {
var newBrand = new Brand({name:namebrand});
productModel.brand = newBrand._id
newBrand.save(function (err, newBrandID){
console.log("newBrandID : "+newBrandID)
brandID = newBrandID.id;
});
}
productModel.save();
});

making the output of "find" using mongodb with nodejs look better

I am using a function to find clients from my mongodb database using node js.
In my query I'm trying to get the function to output the data without the "_id"
but it's not working.
function findClient(Fname,res){
let query = {name:Fname}
dbo.collection("clients")
.find(query,{ _id: 0,name: 1 ,last: 1, age:1})
.toArray(function(err, result) {
if (err) throw err;
result = JSON.stringify(result)
res.render(`./pages/findRes`,{data:result})
console.log(result)
});
}
You don't need to use toArray here.
function findClient(Fname, res) {
let query = { name: Fname }
dbo.collection("clients").find(query, { _id: 0, name: 1, last: 1, age: 1 }, function (err, result) {
if (err) throw err;
result = JSON.stringify(result)
res.render(`./pages/findRes`, { data: result })
console.log(result)
});
}
Basic example here: https://mongoplayground.net/p/WzCaITFhCHM
This should work.

Categories

Resources