Bug - [email protected] with Express for routes with ids
What is the current behavior? This mongoose schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
module.exports = UserModel = new Schema({
_id: {
type: String,
},
firstName: {
type: String,
default: "Jane or John",
required: false,
},
lastName: {
type: String,
default: "Doe",
required: false,
},
email: {
type: String,
default: "[email protected]",
required: true,
},
phone: {
type: Number,
default: 1234,
required: false,
},
created_date: {
type: Date,
default: Date.now,
},
});
When imported into a controller
/*jshint esversion: 6 */
const mongoose = require("mongoose");
mongoose.Promise = require("bluebird");
const UserModel = require("../../data/data-models/userModel");
const User = mongoose.model("User", UserModel);
module.exports = addNewUser = (req, res, next) => {
let addUser = new User(req.body);
addUser.save().then(function (savedUser) {
res.send(savedUser);
});
next().catch((err) =>
res.status().res.json(err, { message: "successfuly added user" })
);
};
module.exports = getUsers = (req, res, next) => {
User.find({}).then(function (userList) {
res.send(userList);
});
next().catch((err) =>
res.status().res.json(err, { message: "successfuly fetched user list " })
);
// Ids not recognised - logs null/ blank
module.exports = getUserById = (req, res) => {
console.log(req.params.userId, "check id"); // to check the id
User.findById({ _id: req.params.userId }, { $set: req.body.userInfo })
.exec()
.then(function (getUser) {
console.log("Response from mongo ", getUser);
res.send(getUser);
})
.catch((err) =>
res
.status()
.res.json(err, { message: "successfully fetched user by id " })
);
};
module.exports = updateUser = (req, res, next) => {
// .route("/api-users/:userId")
User.findByIdAndUpdate({ _id: req.params.userId }, req.body, {
new: true,
useFindAndModify: false,
omitUndefined: false,
})
.exec()
.then(function (updatedUser) {
res.send(updatedUser);
})
.catch((err) =>
res
.status()
.res.json(err, { message: "successfully updated user by id " })
);
};
// DELETE works but conflicts with GET - the 2 dont work together
module.exports = deleteUser = (req, res) => {
// .route("/api-users/:userId")
User.findByIdAndRemove(
{ _id: req.params.id },
{
new: true,
useFindAndModify: false,
}
)
.exec()
.then(function (deletedUser) {
res.send(deletedUser);
})
.catch((err) =>
res
.status()
.res.json(err, { message: "successfully deleted user by id " })
);
};
};
Then configured with CrUD routes
const addNewUser = require("../routes-control/crmControllers");
const getUsers = require("../routes-control/crmControllers");
const getUserById = require("../routes-control/crmControllers");
const updateUser = require("../routes-control/crmControllers");
const deleteUser = require("../routes-control/crmControllers");
const crmRoutes = (app) => {
app
.route("/api-users")
.get((req, res, next, end) => {
// test middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, getUsers)
.post(addNewUser);
app
.route("/api-users/:userId")
.get((req, res, next) => {
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, getUserById)
// .put((req, res) =>
// res.send("/api-users/:userId Update-PUT request successful!")
// )
.put(updateUser)
.delete(deleteUser);
// .delete((req, res) =>
// res.send("/api-users/:userId Delete-DELETE request successful!")
// );
};
module.exports = crmRoutes;
What is the expected behavior? The id routes work when tested in Postman but when the controllers are added with the mongoose schema the id is not recognised as an object or a string - returns null.
One solution was to downgrade to [email protected] but then the server crashes only @5 and above does this code work
/*jshint esversion: 6 */
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
// file paths static files
const path = require("path");
// Site security
const cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const helmet = require("helmet");
// middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
// serve static files
app.use("/", express.static(path.join(__dirname, "../public")));
app.get("/favicon.ico", (req, res) => res.sendStatus(204));
const playerRoutes = require("./apis/routes-config/playerRoutes");
playerRoutes(app);
const crmRoutes = require("./apis/routes-config/crmRoutes");
crmRoutes(app);
// mongoDb setup
const dBUri = process.env.DB_CONNECTION;
mongoose
.connect(dBUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useMongoClient: true,
})
.then(() => {
console.log("conected to mongodb");
})
.catch((error) => {
console.log("mongo error", error);
});
mongoose.Promise = global.Promise;
app.listen(PORT, () => console.log(`your-app listening on ${PORT}`));
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version. mongoose @5.0.15 MongoDB shell version @v4.2.6 node @v11.15.0
The get routes and data working as intended but all the id routes the id not recognised. When the generic routes are commented out, the id routes still do not work - explicitly calling next() and end() on generic routes have also. not solved the challenge as some stackoverflow threads have suggested.
Please clarify what you mean by "mongoose schema the id is not recognised as an object or a string - returns null" and "the get routes and data working as intended but all the id routes the id not recognised", I unfortunately don't understand what's going wrong here. Please be explicit about the observed behavior and the expected behavior.
Hi @vkarpov with a mongoose schema, I understand that an _id as is autogenerated and is of the type ObjectId. However, in an API-end point with a /:id route the console log on the get request returns the _id as null - therefore it is not being recognised as an objectId. A solution on stack overflow was to add the _id as a type of String. Which I have done - code block below (the while schema at the beginning). It still returns null.
_id: {
type: String,
},
I also tried to change this to
_id: {
type: {},
},
To an object this also did not work - the generic get route works but it conflicts with the get route with an id.
app
.route("/api-users")
.get((req, res, next, end) => {
next();
}, getUsers)
.post(addNewUser);
app
.route("/api-users/:userId")
.get((req, res, next) => {
}, getUserById)
The other solution was to downgrade to mongoose v4.7.2 but then the db does not connect from the Express server. I hope this helps?
What is the type of _id on the document you're looking to find in the database?
Also, are you sure you're looking at the right collection? Remember that Mongoose pluralizes your model name to get the collection name by default, so if your model's name is 'User', Mongoose will look in the 'users' collection.