To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name
Related
So I Have some data in my Mongo Database, which I.find() by express and send it to my EJS view. pretty simple. But the problem is when I try to read it using <pre><%=%></pre> i get undefined. Here's the entire code:
The Data Array containing Object in MongoDB:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
Express Code where I get it and send it to EJS:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
and the EJS:
<pre><%= fres.description%> %> </pre>
And Now the BIG CONFUSION: when I replace fres.description with fres._id, It works perfectly fine. but that's it, it doesn't wanna print any other key values. I've been searching far and wide for almost a day now. But nothing helps. this is annoying me now.
PS: console.log(fres.description) is undefined and console.log(fres._id) works fine.
Why? How do I fix this?
please tell me if you need any other code.
Besides the problem with the filter method returns an array, I think you have another problem accessing data from Mongoose response.
This problem is discussed here: Mongoose return data inside _doc object. You can check out my answer with a test code to demonstrate some methods to access data from Mongoose response.
Array.filter returns an array. So, var fres = result.filter(d => d._id == urlID); the variable fres is an array with an object in it.
And if you need only the object in your EJS template, you need to pass just that.
res.render('wallpaper-page',{fres: fres[0]});
Now you can access the description key directly. But I don't understand how fres._id works, it should also be undefined.
When using a get request for all the users in my database (see code below) i only get the "first" user in the database. If i instead try to use the "findOne"-method i get the same user as before no matter what i put in (the username doesn't even have to be in the db it still gives me the same user). I've been trying to understand why this isn't working but can't find any problems with the code. Could it be a problem with db settings or something similar? All help is appreciated!
In AuthController:
// Get all users
AuthController.allusers = function(req, res) {
User.find({}, function(err, users) {
}).then(function(users) {
res.json({users: users});
});
}
In routes:
// GET Routes.
router.get('/users', AuthController.allusers);
Since you are using Sequelizejs, you might want to do findAll.
AuthController.allusers = function(req, res) {
User.findAll().then(function (users) {
res.send({users: users});
}
}
According to the docs:
find - Search for one specific element in the database
findAll - Search for multiple elements in the database
I have been trying to understand why this delete query doesn't work for days, and I just can't see the problem.
I've tried many different delete queries like deleteOne, findOneAndDelete, deleteMany but none of them worked.
I use the "mongodb" client for node.js
mongo.connect(serverAddress, (err, db) => {
//(db connection is ok, server can find and create documents)
var doc = db.collection('myCollection'),
docToDelete = "575807172154b7a019ebf6db";
//I can see the same document id on my database
doc.deleteOne({"_id":docToDelete}, (err, results) => {
console.log(`Request success : ${results.result.ok}, documents deleted : ${results.result.n}`);
//Request success : 1, documents deleted : 0, the document is still on my database
});
}
//the doc var is the same I use to add/find documents (and it works).
When I use the same query in softwares like MongoClient, it works.
I have tried many solutions posted on this site and sorry if the error is too obvious but I'm totaly lost.
Thanks for your help.
The problem is that _id in the database is of type ObjectId, but in your query it's a String. You have to be strict about that, otherwise the query won't match the document.
Try this:
const mongodb = require('mongodb');
...
doc.deleteOne({ _id : mongodb.ObjectId(docToDelete) }, (err, results) => {
...
});
I am calling this function from my android app,
Parse.Cloud.define('addFriendRequest', function(request, response) {
var userObjectId = request.params.userObjectId;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userObjectId });
var relation = Parse.Relation(user, 'friendRequests');
relation.add(request.user);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success("Successfully added friend Request");
}, function(error) {
response.error("An error has occurred")
});
});
And an errror is being thrown of type
TypeError: Cannot call method 'add' of undefined at main.js:10:11
I am relatively new to javascript so any advice would be great. Also the relation friendRequests exists already.
This should work.
Parse.Cloud.define('addFriendRequest', function(request, response) {
Parse.Cloud.useMasterKey();
var userObjectId = request.params.userObjectId;
var user = Parse.User.createWithoutData(userObjectId);
var relation = user.relation('friendRelation');
relation.add(request.user);
user.save().then(function(user) {
response.success("Successfully added friend Request");
}, function(error) {
response.error("An error has occurred")
});
});
Some clarification of what is going on here and why your code did not work.
First of all, it is a good practice to put Parse.Cloud.useMasterKey(); right in the beginning of the function.
I see that you have the objectId of user in the beginning and that you would like to use the user based on its objectId. I order to do that, you should use Parse.User.createWithoutData('yourObjectIdHere') method. What you are actually doing for this step, is that you are creating a new user, rather then creating a reference for the one you already have in the database.
If you want to get a relation of a particular object (User object in your case) your use Parse.Object.relation('putRelationKeyHere'). You are actually creating a new relation instead of accessing the existing one.
I would recommend you to read Parse Javascript Guide in order to learn the recommended techniques.
Given routes
GET /user/42
GET /user/dude
where 42 is user id and dude is username.
So, I want to have method in my controller that return user for both cases. Here it is:
// api/controllers/UserController.js
findOne: function(req, res) {
User.findOne({
or: [
{id: req.params.id},
{username: req.params.id}
]
}).exec(function(err, user) {
if (err) {
return console.log(err);
}
res.json(user);
});
},
When I try to GET /user/42 everything is fine.
When I try to GET /user/dude I get error:
Error (E_UNKNOWN) :: Encountered an unexpected error
error: invalid input syntax for integer: "dude"
It seems like sails refuses to process {id: 'dude'} because of type mismatch.
I am using sails 0.10.5 with sails-postgresql 0.10.9. So what am I doing wrong?
UPD: I do know how to solve problem. Of course I can put if statement to my controller and check what type of parameter it got. Actually, I just created two routes with regexp parameters that point to single method.
My actual problem is why I can not do this with or. Does sails provide such way?
By default, sails get method only supports id numbers. You will need
to define custom routes and implement the relevant api method to
support a get request using a string instead of a number.
Technical Details:
To solve your exact problem, you need to define the following route in your routes.js
module.exports.routes = {
...
'/user/get/:param': 'UserController.findByIDorName',
...
}
This will pass anything after the /user/get/ as the parameter named 'param' to the findByIDorName controller method.
Next you need to check the type of the param and decide if you want to fetch the user info based on the id or the name, so add this function in your userController.js
findByIDorName : function (req, res) {
if (isNaN(req.param)){
//find the user by his username after any validation you need
}
else {
//find the user by his id and return
}
}