I want to use the zunionstore command on sets which i define at runtime, they are fetched dynamically so i never know what the sets are that i have to pass to the function.
syntax of zunionstore:
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
the parsed array contains the names of the sets.
client.zunionstore
(
'out',
parsed.length,
parsed,
function (err, res)
{
console.log(err);
if(!err)
{
client.zrevrange('out', 0, -1, 'withscores', function (err, res)
{
console.log(res);
if(!err)
{
//do stuff
}
});
}
}
);
as you can see i tried to pass the array containing the names but this doesn't work..
the error i get:
[Error: ERR syntax error]
Any ideas on how to solve this?
do you mean that you are having problems passing an array to a function? put all arguments into an array and call apply on the function: Passing an array as a function parameter in JavaScript
so, you have your parsed array, just add to it the other things like your 'out', parsed.length, etc, and call client.zunionstore.apply(this, array).
Related
I am trying to get the object I inserted. I am referring to the example in the
documentation. But I always get an "undefined". What am I doing wrong? Or is it
no longer possible?
In my package.json is the following sqlite3 library "sqlite3": "^5.0.8".
My code (paste and give me the last inserted id)
sql = `INSERT INTO comment_hearts(post_id, comment_id, user_id, CREATED_AT)
VALUES (?,?,?,?)`
db.run(sql, [1, 100, 10, new Date().toString()], (err) => {
if (err) { console.log(err.message)};
console.log("THIS.lastID",this.lastID) // get always undefined
});
You must pass a callback function with function () { ... } for this.lastID to not be undefined.
db.run(sql, [1, 100, 10, new Date().toString()], function(err) {
if (err) { console.log(err.message)};
console.log("THIS.lastID",this.lastID);
});
Dont use arrow function. Pass as callback a function() {...}. The reason is the context of this. The expression of an arrow function has no this of its own.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Hello guys i'm getting this message when i'm trying to delete an entry in my DB.
I have tried JSON.parse on the req.body,switched the routes in my routes file yet nothing seems to work.
this is my controller :
async function removeToy(req, res) {
try {
const { toyId } = req.params
const removedId = await toyService.remove(toyId)
res.send(removedId)
} catch (err) {
logger.error('Failed to remove toy', err)
res.status(500).send({ err: 'Failed to remove toy' })
}
}
this is the service :
async function remove(toyId) {
try {
const collection = await dbService.getCollection('toy')
await collection.deleteOne({ '_id': ObjectId(toyId)})
return toyId
} catch (err) {
logger.error(`cannot remove toy ${toyId}`, err)
throw err
}
}
also added a picture of how the DB looks like:
and the picture of the entire error :
appreciating any kind of help!
In your database you have an object whose _id is of type string.
In your query, you're casting (presumably) a string to an ObjectID, which is an object. Not only is the argument you're passing to ObjectId() not something that it supports (as the error indicates, see below), even if it would be valid, the query would result in 0 hits: after all "TZ23c" !== ObjectId("TZ23c").
Simply change .deleteOne({_id: ObjectId(toyId)}) to .deleteOne({_id: toyId}).
ObjectId() either takes no argument (it will return a new value) or it takes exactly 12 bytes (24 hexadecimal characters), for example: ObjectId("61e16f21f82a9db6a2094e78").
An ObjectId's string representation (ObjectId().toString()) is not an arbitrary string of characters: it's a timestamp, some values that identify which server generated it and some random values to prevent collisions. Not every string is a valid ObjectId.
As the message suggest your toyId passed to the function is with wrong lenght , it must be 12 bytes long , example:
mongos> ObjectId("x448c")
2022-01-14T13:43:51.427+0100 E QUERY [js] Error: invalid object id: length
:
#(shell):1:1
mongos>
The correct is:
mongos> ObjectId("61e16facafe3aa6023c221bb")
ObjectId("61e16facafe3aa6023c221bb")
I am making a server using nodejs & express in which user can request some data and server send response. But, the data is array and I want to send a json response to the user. So, I used forEach() method of array and use Object.assign(), so that I can get object. But the problem is I cannot use 'index' argument of forEach() method while 'value' argument is properly getting used inside the callback function. When I use only 'index' argument, then my code runs ok but I want to use both arguments at the same time.
route.get('/getGPX/:number', passport.authenticate('jwt', { session: false }), (req, res) => {
gpx.find({ username: req.user.username }, (err, result) => {
if (err) console.log(err);
if (result) {
if (result.length === 0) {
res.end();
console.log('ended')
}
else {
var jsonRes = {};
result.forEach((value, index) => {
I can use 'value' but not 'index' from the arguments
jsonRes = Object.assign({ index: value.data }, jsonRes);
})
res.json({data: jsonRes});
}
}
})
I even tried using global var, but even it's not working, how can I use index as well as value argument at the same time
What is the JSON structure that you want ?
if you want a json like :
{
0: "my first value",
1: "second"
}
You just miss [] around index, here you put 'index' as a key not the value of index. So you override the index key in each iteration.
Here is the code that use the value of index as a key in a json.
jsonRes = Object.assign({[index]: value.data}, jsonRes)
See here for a working example with more examples : https://repl.it/#Benoit_Vasseur/nodejs-playground
Object.assign mutates the left-most parameter. it does not produce a new object. Since you are passing a literal object every time the jsonRes is going to be the last result.
Put jsonRes in the left instead - Object.assign(jsonRes, {index: value.data})
You might want to use a simple reduce instead of forEach and Object.assign:
} else {
var jsonRes = result.reduce((r, v, i) => {r[i] = v.data; return r}, {});
res.json({data: jsonRes});
}
I have a document in my mongoDB
I pass the object from my frontend (user should type something in input filed, for example he types 'test':
{'countdown': 'test'}
And then I pass it to my backend and want to check if he typed right
app.post('/answ', function(req, res) {
var query = req.body;
Model.find(query
, function(err, result) {
if (err) throw err;
if (result) {
if(result.length!== 0) {
res.json('ok');
} else {
res.json('not found');
}
} else {
res.send(JSON.stringify({
error : 'Error'
}))
}
})
});
So, if key-value pair exist, backend will return ok, otherwise not found.
It works for such simple object, but if I try to pass something like:
{'apilisttask': { 'port': '1', 'host': '2', 'path': '3', 'query': '4' } }
In this example user has 4 input fields, I gather all answers and pass it to the backend, but it doesn't give me ok even if the answers are right.
Could you please advice maybe a better approach to compare the data or how to fix the second comparison?
Since you are trying to find in an embedded document, you can not query embedded doc like that.
To query embedded doc, you need to do something like this:
Model.find({'apilisttask.port':query.apilisttask.port, 'apilisttask.host':query.apilisttask.host, ...}, function(err, result){
// ---
});
This should do the trick.
When I do a search with "findOneAndUpdate" and one of my search parameters is "undefined" I do not get an error but is the object searched. this is the code:
var q = Q.defer();
var findOneQuery = {
_id: restId,
versionId: document.version // if this parameter is undefined
};
this.findOneAndUpdate(findOneQuery, {$set: document, $inc: {versionId: 1}}, {upsert: true, new: true}, function (updateError, updateDocument) {
if (updateError) {
q.reject(updateError);
}
else {
q.resolve(updateDocument);
}
});
return q.promise;
I think it should return an error if I'm wrong What should I do to search for the two parameters sent and not just by one of them?
You can easily write a wrapper method around findOneandUpdate that would precisely do what you want with your reqs.
function myFindOneAndUpdate(monObj,query,update,options,callback){
//validateINput check if the params in query object are undefined
if(validateInput(query)){
monObj.findOneAndUpdate(query,update,options,callback)
}else{
throw new Error('InvalidInput');
}
}
If parameter is undefined, then mongodb try to find records in which parameter is undefined. So it would not throw any error.
if you want that versionId should be never null/undefined. then you can validate inputs before passing to db query.
You can use this module:
https://www.npmjs.com/package/validator