Why doesn't findByIdAndUpdate update the document? - javascript

I have my problem with the following function
export function updateLine(req: Request, res: Response) {
if (!req.params.id || !req.body) return res.status(400).send({ message: 'Client has not sent params' });
Line.findByIdAndUpdate(req.params.id, req.body, async (err, lineUpdated) => {
console.log("req.params.id", req.params.id)
console.log("lineUpdated", lineUpdated)
console.log("req.body", req.body)
if (err) return res.status(409).send({ message: 'Internal error, probably error with params' });
if (!lineUpdated) return res.status(404).send({ message: 'Document not found' });
if (req.params.id !== lineUpdated.id) await Key.updateMany({ 'line': req.params.id }, { 'line': lineUpdated._id }).exec(err => {
if (err) return res.status(500).send({ message: 'Key Internal Server Error' });
});
return res.status(200).send({ data: lineUpdated });
});
}
What I'm trying to do is just update the document req.params.id with what contains req.body
The responses to the console.log () shown are as follows
req.params.id ACCSEH
lineUpdated {
_id: 'ACCSEH',
name: 'Accesorios (SEH)',
started: 2020-04-21T20:25:10.395Z,
__v: 0
}
req.body { id: 'ACCSEJ', name: 'Accesorios (SEH)' }
I am doing something wrong?
I already know that lineUpdated will return the function to me before the change. I mean when I do the query to see the change nothing has changed
enter image description here

Referring to the documentation:
The field name _id is reserved for use as a primary key; its value
must be unique in the collection, is immutable, and may be of any type
other than an array.
You can not change _id field once it is inserted into the collection

When finding and updating by ID you can't give it an ID in the object - you need to give it an object that has some combination of the other items (name, started, _v).

Related

How to check if data insert is not null with NodeJs?

I have a controller that when i insert data into the database it always inserted. Now i wanna check that if the data i create is null is must report an error.
Here is my code:
// create new car
export async function createCar (req, res) {
const car = new Car({
car_id: id,
name: req.body.name,
color: req.body.color,
brand: req.body.brand,
});
return car
.save()
.then((newCar) => {
return res.status(201).json({
success: true,
message: 'New car created successfully',
Car: newCar,
});
})
.catch((error) => {
console.log(error);
res.status(500).json({
success: false,
message: 'Server error. Please try again.',
error: error.message,
});
});
}
And i check on postman even i let Name is NULL is still inserted. Furthermore, how can i check that COLOR, BRAND if it's null must also report an error. Please help me.
Kato, please follow my boilerplate. I created it with the best practices, and it also provides high-end JOI request validation.
A boilerplate for building production-ready RESTful APIs using Node.js, ExpressJs, Mongoose and Joi (Request Validation)
Node-Express-Mongoose-Joi
For validate before insert
// Validate request
if (!req.body.name)
{
res.status(400).send
({
message: "Name can not be empty!"
});
return;
} else if (!req.body.color)
{
res.status(400).send
({
message: "Color can not be empty!"
});
return;
} else if (!req.body.brand)
{
res.status(400).send({
message: "Brand can not be empty!"
});
return;
}

cut user id mongoose response

I'm trying to response from my backend a piece of user id by using lodash, i tryed with id.slice(2, 9) but i get a response without _id. What i'm doing wrong? thanks in advance.
getUserData: (req, res, next) =>{
User.findById(req.params.userId,
(err, user) => {
if (!user)
return res.status(404).json({ status: false, message: 'User record not found.' });
else
return res.status(200).json({ status: true, user: _.pick(user, ['_id'.slice(2, 9), 'domain', 'store', 'settings']) });
}
);
},
getUserData: (req, res, next) =>{
User.findById(req.params.userId,
(err, user) => {
if (!user)
return res.status(404).json({ status: false, message: 'User record not found.' });
else {
let json = { status: true, user: _.pick(user, ['_id', 'domain', 'store', 'settings']) };
json.user._id = json.user._id.slice(2, 9);
return res.status(200).json(json);
}
}
);
},
Pick the parts you want
Slice the _id to replace it with just the part you want
return the object
Edit:
To cut the ObjectId is necessary first to parse to string, so you need something like this:
var newUserId = user._id.toString().substring(3,user._id.toString().length)
But there is a problem (I think, not tested). If you try to store the cut id into a model object, maybe mongoose don't allow you to add an string (and no valid ObjectId) value instead of ObjectId.
Maybe is neccesary create another object instead of the model with the schema.
Old answer (unrelated) but maybe usefull for somebody:
If you want to hide the result just use select() into your query.
You run a query and then select which fields do you want to get or not into the response.
The proper way to code it is as follows:
query.select({ field1: 1, field2: 1 });
//or
query.select('-field1');
//and many other ways
Docs here

MEAN - mongoose getting the full object using findById

I'm having this little issue/confusion here... I was actually able to get an individual article by their _id using findById(req.params.articleId)
my get request
router.get('/:articleId', function (req, res, next) {
var decoded = jwt.decode(req.query.token);
Article.findById(req.params.articleId, 'keyskeys')
.populate('user')
.exec( function (err, article) {
console.log('see out article too', article)
// if the ID is not found or invalid, return err
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
// if the article was not found anyways
if (!article) {
return res.status(500).json({
title: 'Article not found',
error: { message: 'Article was not found!' }
});
}
return res.json({
success: true,
message: 'successful :id',
article: article,
});
});
});
Postman is returning 200 ok, but the data returned isn't just what I wanted
its just returning the objectID whereas I need it to get the whole object of that particular Id to work with...
I'm kind of confused here, googled around, can't really get my hand on something...
postman is returning
{
"success": true,
"message": "successful :id",
"article": {
"_id": "5b0af26a0321733524c64c91"
}
}
its supposed to return something like
{
"_id" : ObjectId("5b0af26a0321733524c64c91"),
"favoritesCount" : 33,
"title" : "jfdkjkjgfkgfkll",
"description" : "lkfgmfglkgfklgfk",
"body" : "klmfl,,;lvk;lggpog,gf.,gf.gl.",
"username" : "qqqq",
"userId" : ObjectId("5b0af2500321733524c64c90"),
"__v" : 0
}
any help will be greatly appreciated
findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.
Example:
// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );
Functionally, it's the same as calling:
UserModel.findOne({_id: id}, function (err, user) { ... });
for more information refer this Similar Question Link

writing a query and return one value from a database in node js and mongoose

im writing a query in node js, my model of schema has 3 objects( userid, tokenid, mediaid), and i want to find the token id of a certain userid and use it in another function.
my code is as below:
app.get('/registeruser/:userid', function(req, res){
var name = req.params.userid;
user.findOne({userid: name},function(err, users1){
if(!users1){
res.send('Error 404, user not found');
return res.status(404).send();
}
else{
var query = user.find({tokenid: 1});
query.where({userid: name});
query.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});
user is the name of my model.
i run my code and i expect it to return the tokenid but it returns this: []
with these in my database:
userid: 'hgfj1234',
tokenid: 'juiodkdn12345678',
mediaid: ['med10', 'med11']
when i write userid: 'hgfj1234' it gives me this: [] but i want the real tokenid.
if anyone can help me i really appreciate it.
thanks in advance.
You don't need to do additional request to get record from mongodb.
That's enough to use findOne with complex attributes.
Try this:
app.get('/registeruser/:userid', function(req, res) {
var query = {
userid: req.params.userid,
tokenid: {$exists: true, $not: {$size: 0}}
};
user
.findOne(query)
.exec(function(err, User) {
if(err) { // error happen,
console.error(err); // log error
return res.status(500).send({
success: false,
message: 'System error'
}); // respond with 500 status and send json response with success false and message. return will stop execution to go down
}
if(!User) { // response from database was empty or null
return res.status(404).send({
success: false,
message: 'User not found'
}); // respond with 404 status and send json response with success false and message. return will stop execution to go down
}
res.send({
success: true,
tokenid: User.tokenid
}); // and at last everything is ok, we return json response with success and tokenid in response
});
});
attributes in query variable means to request mongodb to give us document with userid defined in request and that has tokenid that is defined and not is empty string (not size 0).
if You still did not getting desired result so check database for existence of necessary document.
If I understand your query right, you will reduce all find() calls to the tokenid with value 1. You will receive only any result, if the user has the token "1".
I suspect you wanted to code a projection, that is the second parameter on find():
var query = user.find({"userid": name});
query.select({"tokenid": 1})
.exec(function(err, result){
if(err){
res.send('erooooooor')
}
else{
res.send('okk')
console.log(result)}
});

Existing property return undefined

I started the implementation of a RESTful API usin node.js, express, and mongodb. Everything went well until now, I've a route to authenticate an user as follow:
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
nickname: req.body.nickname
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({
success: false,
message: 'Authentication failed. User not found.'
});
} else if (user) {
console.log(user);
console.log(user.nickname);
console.log(user.email);
console.log(user.password);
console.log(user.sexe);
if (user.password != req.body.password) {
res.json({
success: false,
message: 'Authentication failed. Wrong password.'
});
} else {
var token = jwt.sign(user, app.get('salt'), {
expiresInMinutes: 1440 // expires in 24 hours
});
res.json({
success: true,
token: token
});
}
}
});
});
The user is retrieved, and loged in the console as follow:
{ sexe: 'H',
email: 'MrPanda#gmail.com',
password: 'bambou',
nickname: 'MrPanda',
_id: 56cb703e7aef3f83c7dac0a7 }
which is perfect, but then, the three following consol.log return the three following lines:
MrPanda
MrPanda#gmail.com
undefined
H
I see absolutely no reason why the password is undefined at this point, I tried to change the attribute name to 'mdp', same issue... Any ideas ? Thanks
If you are using mongoose it does not return a plain JSON object. It is actually a special mongoose object and may not function how you expect.
You have two options:
Convert the mongoose object to a JSON object.
Add {lean: true} to the Users options parameter.
OR JSON.stringify(user)
OR user.toJSON()
Use the proper get() and set() methods (which you should be doing anyways).
user.get('password')
user.get('email')
user.get('name')
Try that and let me know if it doesn't work still.

Categories

Resources