0
votes

I have a very simple schema:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  'name': {type: String, required: true}
});

module.exports = mongoose.model('User', userSchema);

I am creating new users and saving them to the database as follows:

app.get('/profile/:name', (req, res) => {
  const newUser = new User({
    name: req.params.name
  });
  newUser.save((err) => {
    if (err) {
      res.send('Error: ' + err);
    }
  });
  res.redirect('/profile');
});

And then I am rendering 'profile' with all users:

app.get('/profile',
  require('connect-ensure-login').ensureLoggedIn(),
  (req, res) => {
    User.find((err, allUsers) => {
      if (err) {
        res.send('Error: ' + err);
      } else if (allUsers.length === 0) {
        res.send('No users.');
      } else {
        res.render('profile', {user: req.user, allUsers: allUsers});
      }
    });
  });

But I keep getting the following error:

CastError: Cast to ObjectId failed for value "10160168341815704" at path "_id" for model "User"

I am new to MongoDB and Express, so any help would be greatly appreciated! Thanks.

2

2 Answers

0
votes

Try to add '{}' as first parameter in 'find' method:

User.find({}, (err, allUsers) => {
....
0
votes

My guess is you have inserted an _id value manually so mongoose is complaining about it because it can cast that value to an ObjectId.

In your mongo shell try with:

$ db.user.find({ _id: {type: 'int'}})

or even better

$ db.user.find({ _id: 10160168341815704 })

to see which document is with this value 10160168341815704 and delete it.

That should fix your problem.