I am querying from my sails API in my postgres db :
Foot.query("SELECT id FROM foot WHERE foot.date <'"+nowMinus3d+"' AND date >'"+nowMinus4d+"'", function(err, results){
_.each(results.rows, function(result, err){
console.log(result["id"]);
Player.query("SELECT player.user FROM player WHERE (player.statut = 2 OR player.statut = 3) AND player.foot ='"+results.rows["id"]+"'", function(err, players){
console.log(players);
})
})
})
},
Everything works fine until I enter the second query : Player.query, here I keep getting undefined for console.log(players). I tested the query in Pgadmin interface and I think i should be getting an object with [{user: 2}, {user: 1}] somewhere for players.
What am I doing wrong here ?
You're using results.rows["id"] in the second query. Which I guess will be null or underfined.
BTW, you should test the "err" first. And you might want to use "in" instead of sending querys in a loop.
Related
I'm getting stuck on a stubborn bug in my MEPN app.
This pseudo-code is supposed to assemble a Mongoose query from the options submitted in a user form, and then search a collection using that query.
var query = [];
query.push("{name:"+req.body.name+"}");
query.push("{status:{$in:["+req.body.statusarray+"]}}");
query.push("{range:{$gte:"+req.body.min+",$lte:"+req.body.max+"}}");
Collection.find(query, function(error, cursor){
if(error) console.log("ERROR: "+error);
else //do something
})
Instead, it's printing ERROR: ObjectParameterError: Parameter "filter" to find() must be an object, got {name: 'foobar'},{status : {$in : ['1','2','3']}},{range: {$gte:'0',$lte:'100'}}
Using Collection.find(JSON.parse(query), ...)} instead results in SyntaxError: Unexpected token n in JSON at position 1
Then if I encase the query in { } brackets before passing it to JSON.parse(), it prints Unexpected token { in JSON at position 1
Is there something wrong with the way I am constructing this query?
Collection.find() wants an Object, but you are passing it an array of strings, which is why you're getting that error.
You can make an object a lot of ways, but the simplest is to just make an object literal:
var query = {
name: req.body.name,
status: {$in:req.body.statusarray},
range: {$gte: req.body.min, $lte:req.body.max }
}
Im having problems working with the twilio-api for node.
i wrote this code:
let typeArray = ['caller-name','carrier'];
this.client.phoneNumbers(phoneNumberToCheck).get({
type: typeArray
}, (error, number) => {
// working on the number data results
// ...
});
The problem is that i dont get ANY of them(carrier/caller-name) - although passing array to argument 'type' is the way to do it in other languages(php,c#..) but it doesnt work on node.js, instead i get this:
// -> get
{
"caller_name":null,
"country_code":"US",
"phone_number":"+123456789",
"national_format":"(248) 123-456",
"carrier":null,
"add_ons":null,
"url":"https://lookups.twilio.com/v1/PhoneNumbers/+123456789",
"callerName":null,
"countryCode":"US",
"phoneNumber":"+123456789",
"nationalFormat":"(248) 123-456",
"addOns":null
}
note: if i send each one separately (only carrier or only caller-name) - i get the partial information for each.
how can i get both in one request in node.js?
Twilio developer evangelist here.
You should be calling the Lookups API in Node this way:
client.lookups.phoneNumbers.get(phoneNumber)
.fetch({
type: ['carrier', 'caller-name']
},
function(err, result) {
// do something
}
)
The docs are a little lacking in Node.js on the Lookups documentation and I will raise that with the team.
I am pretty new to Nodejs and MongoDB. This might be a simple error, but I cannot seem to update values from DB. I searched far and wide but my syntax is seem to be right. Please help me.
var dataConstruct = {}
dataConstruct[fieldName] = fieldValue;
updateRecordModel.find(dataConstruct , function(err, field) {
if(err) {
logger.error("Error deleting records. Error -" + err)
callback(err, "Error while searching for record.Please cheack the values posted")
}
else {
logger.info("JSON"+JSON.stringify(field[0].Option1));
field[0].Option1="Max";
logger.info("JSON"+JSON.stringify(field[0].Option1));
if(field){
//code to update
}
else{
callback(err, "No such data present")
}
}
}).lean();
Find is returning data . I am using .lean() to get javascript object instead of document model object so that I can modify data. I cannot seem to modify the data returned without using .lean() as is the problem in this post Why can't you modify the data returned by a Mongoose Query (ex: findById)
I tried to find the data and update or resave it, I tried all the update syntax and methods(including find and then save doc again) mentioned in this post https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications but none seem to work,as I cannot modify the data returned
This is the json returned from find
{"_id":"564c29d96bf38ba3039f4844","Option1":"Gary","Option2":"Fred","__v":0}
I need to know how to update this value
This is the code I used for findoneand update
updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, function(err,records) {
if (err) throw err;
console.log(records);
});
In console record is being returned without being updated
You can try after field[0].Option1="Max"; use save method. field[0].save() . I hope it help
Since mongoose 4.0 the returned value by the findOneAndUpdate is always the old document. If you want the new one to be returned (the updated document) you have to pass {new: true} in the options, as stated in their documentation.
You should end up with something like this:
updateRecordModel.findOneAndUpdate({"Option1": "Gary" }, { "Option1": "Max" }, {new: true}, function(err,records) {
if (err) throw err;
console.log(records);
});
I have a collection in my mongo database by the name "user collection". The collection holds entries with one attribute by the name "DBinstaID".
{ "_id" : ObjectId("5595f6be3eaf90ae2d759cc6"), "DBinstaID" : "280430135" }
I am trying to determine whether a new entry has the same DBinstaID value, and if so increase the count of "idCount". The following code is used in my index.js routing file for node.js/express.
var collection = db.get('usercollection');
var checkDuplicate = collection.find({$where: function(){this.DBinstaID === instaID}});
console.log("DUPLICATE STATUS: " + checkDuplicate);
if(!(checkDuplicate)){
idCount++;
}
However, the checkDuplicate variable is simply set to [object Object] instead of the boolean true or false. How can I search the collection and return a boolean?
Thank you in advance for the help.
The collection.find() method is asynchronous, this means you can't get the results right away, and you need to handle anything dependant on these results directly in the callback.
I strongly advise you to have a good read of mongoosejs's docs (at least the code examples), and to take a look at basics of asynchronous programming in node.js (a google search away).
You can use collection.findOne() to get only one result :
var collection = db.get('usercollection');
collection.findOne({DBinstaID: instaID}, function(err, user) {
// don't forget to check for errors here, masked for clarity
console.log("DUPLICATE STATUS: ", user);
if(user) {
idCount++;
}
// rest of the code
});
In the MEAN app I'm currently building, the client-side makes a $http POST request to my API with a JSON array of soundcloud track data specific to that user. What I now want to achieve is for those tracks to be saved to my app database under a 'tracks' table. That way I'm then able to load tracks for that user from the database and also have the ability to create unique client URLs (/tracks/:track)
Some example data:
{
artist: "Nicole Moudaber"
artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
source: "soundcloud"
stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3?client_id=7d7e31b7e9ae5dc73586fcd143574550"
title: "In The MOOD - Episode 14"
}
This data is then passed to the API like so:
app.post('/tracks/add/new', function (req, res) {
var newTrack;
for (var i = 0; i < req.body.length; i++) {
newTrack = new tracksTable({
for_user: req.user._id,
title: req.body[i].title,
artist: req.body[i].artist,
artwork: req.body[i].artwork,
source: req.body[i].source,
stream: req.body[i].stream
});
tracksTable.find({'for_user': req.user._id, stream: req.body[i].stream}, function (err, trackTableData) {
if (err)
console.log('MongoDB Error: ' + err);
// stuck here - read below
});
}
});
The point at which I'm stuck, as marked above is this: I need to check if that track already exists in the database for that user, if it doesn't then save it. Then, once the loop has finished and all tracks have either been saved or ignored, a 200 response needs to be sent back to my client.
I've tried several methods so far and nothing seems to work, I've really hit a wall and so help/advice on this would be greatly appreciated.
Create a compound index and make it unique.
Using the index mentioned above will ensure that there are no documents which have the same for_user and stream.
trackSchema.ensureIndex( {for_user:1, stream:1}, {unique, true} )
Now use the mongoDB batch operation to insert multiple documents.
//docs is the array of tracks you are going to insert.
trackTable.collection.insert(docs, options, function(err,savedDocs){
//savedDocs is the array of docs saved.
//By checking savedDocs you can see how many tracks were actually inserted
})
Make sure to validate your objects as by using .collection we are bypassing mongoose.
Make a unique _id based on user and track. In mongo you can pass in the _id that you want to use.
Example {_id : "NicoleMoudaber InTheMOODEpisode14",
artist: "Nicole Moudaber"
artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
source: "soundcloud"
stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3? client_id=7d7e31b7e9ae5dc73586fcd143574550"
title: "In The MOOD - Episode 14"}
_id must be unique and won't let you insert another document with the same _id. You could also use this to find the record later db.collection.find({_id : NicoleMoudaber InTheMOODEpisode14})
or you could find all tracks for db.collection.find({_id : /^NicoleMoudaber/}) and it will still use the index.
There is another method to this that I can explain if you dont' like this one.
Both options will work in a sharded environment as well as a single replica set. "Unique" indexes do not work in a sharded environment.
Soundcloud API provides a track id, just use it.
then before inserting datas you make a
tracks.find({id_soundcloud : 25645456}).exec(function(err,track){
if(track.length){ console.log("do nothing")}else {//insert}
});