I like to store mongodb queries as string. I would like to load and execute them. How can I convert the parameter object used in find to a string without loosing information?
I have already tried to use JSON.stringify and JSON.parse, but it seems, that JSON.parse does not revert JSON.stringify completely.
historyCollection.find({"date":{$gte:new Date("2018-12-20 13:47:57.461Z")}, $or:[{"source":2}, {"source":3}]}).limit(4).toArray(function (err2, result2) {
// Do Stuff
});
Related
First time working with MongoDB. This query works for me in cmd line:
db.secrets.update({_id: ObjectId("5f767cd481cea1687b3dbf86")}, {$set: {secret_rating: 5}})
However, updating a record using essentially the same query on my node server is not completing this task when pinged. Am I wrong in trying to query for a record like so in my model? ObjectId obviously isn't native to my server.
db.secrets.update({_id: "5f767cd481cea1687b3dbf86"}, {$set: {secret_rating: 5}})
Assuming you're using the Nodejs Mongodb driver and not some ORM (since it hasn't been specified), two points of concern:
As far as my knowledge serves, if you have a connection object to your desired database in the db variable, you cannot reference collections directly such as you've done with db.secrets; you must instead use the collection method like so:
const secrets = db.collection("secrets");
secrets.find({
/*your query here*/
}).then((results) => {})
So, unless you've assigned db.secrets with db.collection("secrets") you should be getting an error, Cannot read property "update" of undefined. But I'm going to assume you've got the collection object in db.secrets since you did not mention you're getting that error.
You seem to be using a string instead of an ObjectID object. You can import the ObjectID constructor from the nodejs driver like so:
const ObjectID = require('mongodb').ObjectID
Then in your query, you will have to make a new ObjectID to get the correct result:
db.collection("secrets").find({
_id: new ObjectID("5f767cd481cea1687b3dbf86")
}).then((results) => {})
NOTE: The ObjectID constructor will throw an error if the string supplied to it is not a valid, 24-char hex string, so, if you're getting the id string as an input from somewhere (say, as a parameter in an API or as a command line argument), you might want to wrap it in a function that handles that error.
I'm using Monk to connect to to MongoDB from NodeJS.
I am trying to pull an item from an array, and for that purpose I'm using
db.collection('MYCOLLECTION').update({_id:id},{$pull:{reviews:{userId:userId}}, function(err,data){
console.log(data);
})
When I execute this sentence directly in Mongo (through the console), the function returns an object with three properties:
nMatched
nUpserted
nModified
However, when I do the same thing using monk, I am only getting a value '1' which I supposed is the value of the property nMatched. Is there a way for me to get the nModified property?
I am using Node for fetching data from MySQL. In database, i got record like : 2013-08-13 15:44:53 . But when Node fetches from Database , it assigns value like 2013-08-19T07:54:33.000Z.
I just need to get time format as in MySQL table. Btw ( My column format is DateTime in MySQL)
In Node :
connection.query(post, function(error, results, fields) {
userSocket.emit('history :', {
'dataMode': 'history',
msg: results,
});
});
When retrieving it from the database you most likely get a Date object which is exactly what you should work with (strings are only good to display dates, but working on a string representation of a date is nothing you want to do).
If you need a certain string representation, create it based on the data stored in the Date object - or even better, get some library that adds a proper strftime-like method to its prototype.
The best choice for such a library is moment.js which allows you to do this to get the string format you want:
moment('2013-08-19T07:54:33.000Z').format('YYYY-MM-DD hh:mm:ss')
// output (in my case on a system using UTC+2 as its local timezone):
// "2013-08-19 09:54:33"
However, when sending it through a socket (which requires a string representation) it's a good idea to use the default one since you can pass it to the new Date(..) constructor on the client side and get a proper Date object again.
So, I am receiving some JSON data from a client to my Node.JS server. I want to insert that json into my MongoDB instance using Mongoose.
I can insert the JSON as-is, and it works great, because it's just text. However, I want to parse it before insertion so that when I extract it later it will be all nice and neat.
So, this works:
wordStream.words.push(wordData);
And this doesn't:
wordStream.words.push(JSON.parse(wordData));
So, should I even want to parse the JSON before insertion?
And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.
Here is the JSON:
{ word: 'bundle',
definitions:
[ { definition: 'A group of objects held together by wrapping or tying.',
partOfSpeech: 'noun' } ],
urlSource: 'testurl',
otherSource: '' }
And the error when I try to parse
/Users/spence450/Documents/development/wordly-dev/wordly-server/node_modules/mongoose/lib/utils.js:409
throw err;
^
SyntaxError: Unexpected token o
Ideas?
So, should I even want to parse the JSON before insertion?
Convert the strings to JSON objects will benefit you later, when you need to make queries in your MongoDB database.
And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.
You aren't receiving JSON documents. JSON documents must contain the keys quoted.
You can:
Use a library that recognizes invalid JSON objects (please don't)
Use eval (this is a security issue, so don't do it)
Fix the source of the problem, creating real JSON objects. This isn't difficult, you can see the JSON features here
Must be missing something here, but I'm using Node_redis as Node.js client for Redis.
I'm testing Redis' Lrange command which per that doc returns a 'multi-bulk reply'.
From the node_redis docs this gets exposed as a 'JavaScript Array of node Buffers' in Node.
That's all pretty and all, but what are node buffers and more importantly, how do I read them in Node.js? I just want to transform them to an array of string (json) and from there to an array of object literals.
For ref, grabbing the first element of the array buffer[0] and printing it (trying all kinds of things:
console.log(multibulk[i]) -> [object Object]
console.log(multibulk[i].toString("binary")) -> [object Object]
etc.
thanks.
EDIT:
I verified the data is actually there in Redis (and is not stored as the String [object Object] as I began to expect). In Java when using JRedis' lrange command I get a List < String >. The first result of that list gives me the correct String as expected.
Just to close this:
as part of a kind of locking-mechanism I made sure a key was written to in Node. Stupidly I did this by inserting an object literal without stringifying it. This caused all later inserts in the list to fail.