Working with Express and Mongoose, and I'm writing an Update route, and I seem to have hit a wall with this route. I've tried to find the object being requested via:
router.patch('/:insiderId', (req, res) => {
Insider.findById(req.params.insiderId)
.then(insider => {
insider = Object.assign({}, insider, req.body);
insider
.save()
.then(updated => {
res.json(updated);
})
.catch(err =>
res
.status(400)
.json({ error: 'error updating insider', originalError: err })
);
})
.catch(err => {
console.error(err);
res.status(400).json({
error: 'error finding insider to update.',
originalError: err
});
});
});
But I'm still given an error stating that Cast to ObjectId failed for value \"5b16d9e9119bef28908f49c\" at path \"_id\" for model \"insiders\"
I did a little reading, and thought that findById would automatically cast the objectid, but it doesn't appear to be doing that.
Is my code wrong?
Related
I am getting this error when I call this controller, Seems like they can't recognize .create method of the model,
How to import sequelize so that I can use it
const db = require("../Models/m_user");
const M_user = db.m_user;
exports.registerUser = (req, res) => {
if (!req.body.user_id) {
res.status(400).send({
message: "Content can not be empty!"
});
return;
}
// Register a user
const user = {
User_ID: req.body.user_id,
User_Password: req.body.user_password
};
// Save User in the DB
M_user.create(user)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while injection"
});
});
};
It seems to me that your m_user is stored in the db variable - that what your import line suggests. So you are trying to access m_user.m_user?
I'm started working on my very first API using Mongo, Express and Node. When i tried to make API endponit for one specific user, console throw error ReferenceError: err is not defined. An error appears in the method I already used for auth part, and there it worked fine. The part of code where is the error, on line 5:
exports.userById = (req, res, next, id) => {
User.findById(id).exec(() => {
if(err || !user) {
return res.status(400).json({
err: "User not found"
});
}
req.profile = user //adds profile object in req with user info
next();
});
}
Also, the part of code where I tried to get a single user:
exports.getUser = (req, res) => {
req.profile.hashed_password = undefined;
req.profile.salt = undefined;
return res.json(req.profile);
}
I don't think the problem could be here, but there is also route line from routes file
router.get("/users/:userId", authController.requireSignin, userController.getUser);
Thanks everyone for the help!
I'm pretty sure err comes from exec:
User.findById(id).exec(err => {...});
Edit I guess you want to search by id and return something. Try this.
User.findById(id, (err, user) => {
// if error display errort
if(err) console.error(err);
// if user do not exists
if(!user) {// what is user ? the doc result ?
return res.status(400).json({
"err": "User not found" // i think use ""
});
}
req.profile = user //adds profile object in req with user info
next();
});
I have an object i need to parse to React.
I'm trying to get the "rows" object (in the node function) over to a React State.
The 2 piece of code below are on different pages!
The other issue is
GET http://localhost:3000/new net::ERR_CONNECTION_REFUSED
I am currently running these both locally
React http://localhost:3001/
Node - http://localhost:3000/
There have been SIMILAR questions to this but I can't find an answer with both issues!
Thanks
router.get("/new", (req, res) => {
let parentList = sql.fetchAllParents(function(err, rows) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:3001");
if (err) throw err;
res.render('new', {parents: rows});
});
});
componentDidMount() {
fetch(`http://localhost:3000/new`).then(response => {
console.log(response)
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data,'data');
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}
Send response from node "new" api. Like this:
router.get("/new", (req, res) => {
......
......
res.send({status:200,parents:data})
});
I'm currently working on my first node.js rest api with express, mongodb (atlas cloud) and mongoose, when i try to make a .remove request i get this error:
{
"error": {
"name": "MongoError",
"message": "Cannot use (or request) retryable writes with limit=0",
"driver": true,
"index": 0,
"code": 72,
"errmsg": "Cannot use (or request) retryable writes with limit=0"
}
This is my request:
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
The findOneAndRemove() function would work more accordingly since its specific to the filtering method passed in the function .findOneAndRemove(filter, options) to remove the filtered object. Still, if the remove process is interrupted by the connection the retryRewrites=true will attempt the execution of the function when connected.
More information here
When using retryRewrites set to true tells the MongoDB to retry the same process again which in fact can help prevent failed connections to the database and operate correctly, so having it turn on is recommended.
More info here
If you are using Mongoose 5^ and MongoDB 3.6 your code is better written like:
mongoose.connect('mongodb.....mongodb.net/test?retryWrites=true', (err) => {
if(err){
console.log("Could not connect to MongoDB (DATA CENTER) ");
}else{
console.log("DATA CENTER - Connected")
}
});// CONNECTING TO MONGODB v. 3.6
router.delete('/:productId', (req, res, next) => {
const id = req.params.productId;
Product.findOneAndRemove({ _id: id })//updated function from .remove()
.exec()
.then(result => {
res.status(200).json({
message: "Product Removed Successfuly"
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
})
}); ;
});
I just changed the true to false in retryWrites=true and it worked. Is that a good approach? Or there is a better way to solve this problem?
retryWrites=true is a good thing, a workaround for this incompatibility is to use findOneAndRemove instead of remove (looks like you're using mongoose)
I am currently checking out Vue and am doing a little refactor on a personal project.
I am running into some problems with my API.
The two technologies involved are axios which I am using to send requests to my API, which talks to a postgres database using pg-promise.
The api call...
function add (entry, cb) {
const length = entry.content.length
entry.title = `${entry.content.substring(0, 32)}`
axios.post('/api/notes', entry).then(cb)
}
here, entry is and object { title, content, prio, status, context }
the pg-promise endpoint
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body)
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}
here, req.body is undefined
I don't know why I am getting undefined.
Does this error log help?
I was reading through the documentation at axios and could not seem to find anything wrong with my api call, figured I would post something here.
Thanks!
req.body It has the following structure [{.....}]
for pg-promise need {....}
Solution to the problem req.body[0]
export const createNote = (req, res, next) => {
db.none('insert into entries(title, content, prio, status, context)' +
'values( ${title}, ${content}, ${prio}, ${status}, ${context})',
req.body[0])
.then(() => {
res.status(200)
.json({
status: 'success',
message: 'Inserted one entry'
})
}).catch(err => next(err))
}