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 }
}
Related
I am using sqlite3 and nodeJS, and querying a database. I want to copy the queries into a json file. I run into problems with the json file having strings and objects. Why does my JSON file contain:
[object Object]
Here is my code:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}rows.forEach((row) => {
arr_string = JSON.parse(JSON.stringify(row));
fs.writeFile("tempo.json", arr_string, function(err){
});
console.log(arr_string);
});
});
I would like to eventually use ajax requests for these entries.
arr_string = JSON.parse(JSON.stringify(row));
//^---------^--- This is parsing the string back to a new object.
You are parsing the stringified item to a new Object, hence the node.js file writer is trying to write the object to the write stream, resulting in interpreting it as [object Object].
Just omit the JSON.parse, so that the stream will effectively be a string instance:
arr_string = JSON.stringify(row);
Additionally, you should aggregate the result and write it only one time, or append to the file:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}
let _strings = [];
const newline_separator = ''; // <-- use whatever separator you need.
rows.forEach((row) => {
arr_string = JSON.stringify(row);
console.log(arr_string);
_strings.push(arr_string);
});
fs.writeFile("tempo.json", _strings.join(newline_separator), function(err){});
});
Since it's a json, I would suggest you to provide us a more precise input, so that we can guess what the expected result is.
I think while storing JSON data into SQLite, you're not stringifying it. If you directly store JSON data into SQLite it'll store like [object Object] format. My suggestion is to stringify the data while storing in SQLite. And while retrieving only parse it. Then your problem will solve.
arr_string is actually not a string, as you JSON.parse d it. Remove the JSON.parse call.
The JSON.stringify() method converts a JavaScript value to a JSON string
arr_string = JSON.stringify(row);
"the problem now with doing that is now the JSON file only writes the last row (and i queried 4) and also I cannot call arr_string.caphi because its not an object anymore"
Create an empty array(list) and push each result of query in array.And then
finally convert it into JSON.
sample code :
var rows=[{"holla":"bolla"},{"holla":"bolla1"}];
console.log(JSON.stringify(rows));
JSON.stringify() takes JSON object and returns String
JSON.parse() takes String and returns JSON object
try :
rows.forEach((row) => {
arr_string = JSON.stringify(row); // 'row' data is converted to String
fs.writeFile("tempo.json", arr_string, function(err){
});`
I'm trying to send some data along with my ejs file. The data I need to send is an array of json. I've tried using the code below but i'm confused as to why it's not working when I try to send the result of my query.
I've used the following code
var objIds = [obj_id1, obj_id2....] //assume these are object ids
Model.find({
_id : {
$in: objIds
}
}, function(err, doc){
console.log(doc); //doc returns an array of json
var test = [{
"hi":"bye"
}];
res.render('index', arrayOfResults: test});
});
The above code works when I send test but it gives me many errors on the client side when I send doc (the result of the find query). Both test and doc are array of json yet only test works without errors. Does anyone know why?
edit: i should note that the json inside doc would have the following format:
{
field1: [object]
field2: String
}
I'd like to query the API for my Intercom.io app and get a subset of users that have a specific nested key value pair.
The client.users.listBy() works but only for keys that are a direct property of the user object, for instance client.users.listBy({ email: someUsersEmail#domain.com }) works just fine because email is a property directly on the user instance.
My user data is structured like this
user = {
...
email: someUsersEmail#domain.com,
...,
customer_attributes: {
...,
affiliate_code: 'someAffiliateCode',
...
},
...
}
and I would like to find all the users that have customer_attributes.affilate_code equal to affiliate_code: 'someAffiliateCode'.
I'd like to query the API like this:
client.users.listBy({customer_attributes.affiliate_code: 'someAffiliateCode'}, function(err, resp) {
if (err) throw err
console.log(resp)
})
But I'm getting this error
client.users.listBy({customer_attributes.affiliate_code: 'onetouch'}, function(err, resp) {
^
SyntaxError: Unexpected token .
Does anyone know how I can query the Intercom API for nested Key value pairs like in the way described above? Thank you!
As the interpreter hints, that "." in the key name is not valid JavaScript.
The only way to accomplish what you are looking for is to pre-define a Segment in the Intercom UI with "affiliate_code = onetouch". Then you can programmatically list users using that Segment ID. https://developers.intercom.io/reference#list-by-tag-segment-company
client.users.listBy({ segment_id: 'foo' }, callback);
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.
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);
});