Mongoose for Nodejs Express:强制转换为objectid失败

时间:2022-02-05 02:33:33

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"

CastError:对于模型“User”,路径为“_id”的值为“10160168341815704”的CastI为ObjectId失败

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

我是MongoDB和Express的新手,所以任何帮助都将不胜感激!谢谢。

2 个解决方案

#1


0  

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

尝试在“find”方法中添加“{}”作为第一个参数:

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

#2


0  

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.

我的猜测是你手动插入了一个_id值,所以mongoose抱怨它,因为它可以将该值转换为ObjectId。

In your mongo shell try with:

在你的mongo shell中尝试:

$ 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.

查看具有此值的文档10160168341815704并将其删除。

That should fix your problem.

这应该可以解决你的问题。

#1


0  

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

尝试在“find”方法中添加“{}”作为第一个参数:

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

#2


0  

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.

我的猜测是你手动插入了一个_id值,所以mongoose抱怨它,因为它可以将该值转换为ObjectId。

In your mongo shell try with:

在你的mongo shell中尝试:

$ 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.

查看具有此值的文档10160168341815704并将其删除。

That should fix your problem.

这应该可以解决你的问题。