【问题标题】:Mongoose for Nodejs Express: cast to objectid failed for value用于 Nodejs Express 的 Mongoose:转换为 objectid 的值失败
【发布时间】:2018-09-13 12:16:35
【问题描述】:

我有一个非常简单的架构:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

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

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

我正在创建新用户并将其保存到数据库中,如下所示:

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');
});

然后我将向所有用户呈现“个人资料”:

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});
      }
    });
  });

但我不断收到以下错误:

CastError:对于值“10160168341815704”,转换为 ObjectId 失败 模型“用户”的路径“_id”

我是 MongoDB 和 Express 的新手,非常感谢任何帮助!谢谢。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 您在配置文件呈现期间收到此错误,对吗?
    • 也尝试清空用户集合。也许你已经损坏了其中的数据。
    【解决方案2】:

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

    在你的 mongo shell 中尝试:

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

    甚至更好

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-24
      • 2021-09-05
      • 2021-03-09
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-18
      • 2021-03-14
      相关资源
      最近更新 更多