why object variable property did not work in nodejs - javascript

I have a utility function which pass parameters 'name page callback' to the function. Why not work as i tried so many times?
PLUS: seems 'query.tag_id = name' work for me but why query[name] = name did not work so that i can pass whatever name i like;That's, i want to pass the variable /name/ as the property name so that i can use whatever name i like. For example, i can find posts by user_id when i pass user_id variable as the name value. Also i can find posts by its tag_id when i pass tag_id variable as the name value so it's much more flexible than when i use 'query.user_id = name' to do it ,where the name can only be user_id variable or value
NO LIBRARY USED EXCEPT EXPRESS AND NODEJS WITH CONNECT-FLESH, MONGOOSE ETC.
// post_proxy/post.js
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTen: (name,page,callback)=>{
var query = {};
//name = query;
if(name){
query[name] = name;
console.log('query[name] is'+ Object.keys(query));
}
Post.count(query, ( err, count)=>{
if (err) {
return callback(err);
}else{
console.log( `Number of posts: ${count} . query is ${query}` );
Post.find(query).skip((page-1)*10).limit(10).sort({created_at: -1}).exec((err,posts)=>{
if (err) {
return callback(err);
}
console.log('Posts inthe getTen function is: '+posts);
const modifiedPosts = posts.map(post=>{
return post.processPost(post);
});
console.log('modifiedPosts: '+modifiedPosts);
callback(null, modifiedPosts, count);//provide the params(caluated values),and what to do? you need to figure it out yourself
});
}
});
}
// controller/post.js:
"use strict";
let moment = require('moment'),
Post = require('../models/Post'),
User = require('../models/User'),
Comment = require('../models/Comment'),
postProxy = require('../db_proxy/post'),
tagProxy = require('../db_proxy/tag');
module.exports = {
getTagsPost: (req,res)=>{
const tag_id = req.params.tag_id;
const page = req.query.p ? parseInt(req.query.p) : 1;
//let loginedUser;
console.log('entering into the tagpost');
postProxy.getTen(tag_id, page, (err, posts, count)=> {
if (err) {
console.log('some error with getting the 10 posts:'+ err);
//next(err);
posts = [];
}
// if(req.user){
// loginedUser = req.user.processUser(req.user);
// }
//userProxy.getUserById(user_id, theuser=>{
console.log('tag posts for'+ tag_id +posts);
res.render('post/tagPosts', {
title: 'specific tag page',
user: req.user ? req.user.processUser(req.user) : req.user,
//postUser: req.user ? (req.user._id == user_id ? loginedUser : theuser) : theuser,
posts: posts,
page: page,
isFirstPage: (page - 1) == 0,
isLastPage: ((page - 1) * 10 + posts.length) == count,
messages: {
error: req.flash('error'),
success: req.flash('success'),
info: req.flash('info'),
}, // get the user out of session and pass to template
});
});
},
...
}
//route:
router.get('/tag/:tag_id', post.getTagsPost);
UPDATE:
Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}

UPDATE: Did not find an answer so i change it to the following and solve the problems:
getTen: (name,tag_id,user_id,page,callback)=>{
var query = {};
if(name){
if(user_id){
query.user_id = name;
}else{
query.tag_id = name;
}
console.log('query[name] is'+ Object.keys(query));
}
...
}

Related

Node js , cannot retrive data from sqlight3 table

async function get_info(compName) {
let company = {
name:""
, activityNumber:""
, siret :""
, adresse :""
, tva :""
, logo:0
};
buff = await db.all("SELECT * FROM company WHERE name = ?", [compName], (err, rows) => {
if (err) {
console.log(err)
return err;
}
rows.forEach(element => {
console.log(element.name) // WORK
company.name = element.name;
company.activityNumber = element.activityNumber;
company.adresse = element.adresse;
company.logo = element.logo;
company.siret = element.siret;
company.tva = element.tva;
});
});
console.log(" ... " + company.name) // DOSENT WORK
return company;
}
I'm trying to get company fill and get data out of my database.
The first console.log() is good but not the second one, it's empty, and the object it returns have defaults values, there will be only one element who will match "WHERE name = ?" so I don't worry about erasing the value.

How to assign variable of outer function from inner function

I am working on node.js library called node-geocoder. I am trying to create a function which will return only country name. My code is given below:
const NodeGeocoder = require('node-geocoder');
var NodeGeocoderOptions = {
provider: 'google',
// Optional depending on the providers
httpAdapter: 'https',
apiKey: gmapkey,
formatter: null
};
var geocoder = NodeGeocoder(NodeGeocoderOptions);
// get country
function getCountry(lat, long){
country_name = "";
geocoder.reverse({lat:lat, lon:long}, function(err, res) {
// country_name = res[0].country;
country_name += res[0].country;
});
console.log("Country Name is " + country_name);
return country_name;
}
I am getting the response.how can i return country name.
Thanks in advance.

Storing value to indexedDB if it is not defined

I'm trying to check if there is a record of 'uid' in indexed db from a service worker. If it's not defined, I need to add a value to it.
This is my code, I already tried in some ways that I found around other questions and sites, but none worked.
function checkUid() {
console.log('checking uid...');
var request = indexedDB.open('db',1);
request.onsuccess = function(event) {
var db = event.target.result;
var store = db.createObjectStore('Users', {keyPath:"users"});
var transaction = event.target.transaction;
db.transaction( '' ).objectStore( '' ).get( 'uid' ).onsuccess =
function(uid)
{
if (uid) {
console.log('uid found!');
console.log(uid);
console.log('uid end');
} else {
console.log('not found!');
db.transaction( '' ).objectStore( '' ).set( 'uid', 'aaaaa' );
console.log('uid end');
}
}
}
How can I do this?
This code opens the database with the name example, creates the object store called users if needed, gets the object with the key x123 from that store, and creates the object if it doesn't already exist.
function checkUid() {
let openRequest = indexedDB.open("example")
openRequest.onupgradeneeded = () => {
console.log("update needed")
openRequest.result.createObjectStore("users")
}
openRequest.onsuccess = () => {
console.log("opened database")
let store = openRequest.result.transaction("users", "readwrite").objectStore("users")
let uid = "x123"
let getRequest = store.get(uid)
getRequest.onsuccess = () => {
let result = getRequest.result
if (result) {
console.log("found:", result)
} else {
console.log("not found")
store.add("aaaaa", uid)
}
}
}
}
Use put() instead of set(), it will update the entry, or create one if it doesn't exist.
https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put

Mongoose - Referencing another model using require

What I'm trying to do is to update one collection, Prize, and then based on the result from that update another collection, League.
I have the following code:
app.post('/auth/prize/:prizeId', function(req, res) {
console.log('POST /auth/prize/' + req.params.prizeId);
if (req.user) {
var mess = 'JOINED';
var query = {...};
var update = {...};
Prize.findOneAndUpdate(query, update, function(err, result) {
if (err || result === null) {
mess = 'ERROR Incorrect password';
res.send(mess);
return;
}
var League = require('./leagues_api');
var queryL = {...};
var updateL = {...};
League.findOneAndUpdate(queryL, updateL, function(e, r) {
if (e || r === null) {
mess = 'ERROR Incorrect password';
}
res.send(mess);
});
});
} else {
res.send(401, 'Not Admin!');
}
});
So, the issue is that I am seeing an error:
[TypeError: Object #<Object> has no method 'findOneAndUpdate']
I have two separate files to keep everything easy to manage, so I have this file, prizes_api.js, and another file, leages_api.js, which has defined it in the Schema and the Model for League:
var leagueSchema = new mongoose.Schema({...});
var League = mongoose.model('League', leagueSchema);
I use this same style elsewhere, but for some reason in this file I am seeing the error failure. Any advice on this please?
Thank you, Gary.
If calling require('./leagues_api') isn't returning the League model, then your module.exports isn't set up right in that file.
It should look like the following:
module.exports = League;

Node JS Loop Through Array Before Creating Property

I have a JSON input which contains data linking it to a secondary model (Users). I need to loop through listingData.Agents to get the index ID and then look up this index id to get the user. I push this to the user id to an array but due to the async the array is blank when the create property function is run. How you manipulate and get data from the array and then run the create once all your data is in place.
Thanks.
exports.createProperty = function(req,res,next) {
var listingData = req.body;
listingData.User = [];
_.forEach( listingData.Agents , function(n, key) {
User.findOne({ agentId : n.AgentId},function(err,user) {
listingData.User.push(user._id);
});
});
Property.create(listingData, function(err,property) {
if (err) {
res.status(400);
return res.send({reason:err.toString()});
}
res.send(req.property);
})}
If you don't mind introducing new library into your code, node-async could solve your problem.
Using node-async, you code would be:
var async = require('node-async')
exports.createProperty = function(req,res,next) {
var listingData = req.body;
listingData.User = [];
async.each(listingData.User,
function(n, key) {
User.findOne({ agentId : n.AgentId},function(err,user) {
listingData.User.push(user._id);
});
},
function (asyncErr){
//handle asyncErr first
Property.create(listingData, function(err,property) {
if (err) {
res.status(400);
return res.send({reason:err.toString()});
}
res.send(req.property);
});
});

Categories