【问题标题】:mongoose findByID returning undefined猫鼬 findByID 返回未定义
【发布时间】:2018-02-05 00:11:00
【问题描述】:

当尝试使用 findById 从 DB 记录数据时,我得到了 undefined 的返回值。

// Get single article
app.get('/article/:id', (req, res) => {
  Article.findById(req.params.id, (err, article) => {
    console.log(article);
    return;
  });
});


//Article Schema
let articleSchema = mongoose.Schema({
    title: { type: String, required: true }, 
    author: { type: String, required: true},
    body: { type: String, required: true}
});

let Article = module.exports = mongoose.model('Article', articleSchema)

我查了一些东西,我得到了它,但我不确定这是否是正确的方法

所以我发现如果我使用findOne() 并传入Article.id 我会得到我想要的结果,但这是正确的做事方式吗?

我觉得article.id 应该由req.params.id 传递,但是当我将它传递给findOne() 时,我收到一条错误消息:

Error: Invalid argument to findOne(): 'article_id'

【问题讨论】:

  • 尝试注销err参数
  • 这是我得到的:CastError: Cast to ObjectId failed for value "article_id" at path "_id" for model "Article
  • 我当前面临的错误是,当我尝试记录文章值时,我得到一个未定义的值并出现错误:message: 'Cast to ObjectId failed for value "article_id" at path "_id" for model "Article"' 我确实遇到了错误命名参数的问题,但这一直是已修复,我可以让它显示使用 Articles.find() 的文章,但是在尝试使用 Article.findById 时会出现问题
  • 这是完成的错误是在索引 html 我在传递参数并将它们作为字符串传递时犯了一个错误,这就是它无法读取 id 的原因,当我发现这个时检查了索引文件。继续下一步

标签: javascript node.js mongodb mongoose


【解决方案1】:

您是否从您的数据库中提取了正确的 ID,在将您发送到 /article/:id 的链接上。我遇到了同样的问题,正如我之前在基本数组索引上学到的并转移到了 MongoDB。我只需要更新一个字符以包含 MongoDB 语法的“_id”而不是“id”的下划线。

在我的 HTML 呈现页面上为我工作的正确代码如下:

<a href={`/article/${article._id}`}>

我一开始给我一个未定义的结果如下:

<a href={`/article/${article.id}`}>

【讨论】:

    【解决方案2】:

    型号

    const  mongoose  =  require('mongoose')    
    const  validator  =  require('validator')   
    
    
    const  User  =  mongoose.model('User', {
    
    name: {
    
    type:  String,
    
    required:  true,
    
    trim:  true
    
    },
    
    email: {
    
    type:  String,
    
    required:  true,
    
    trim:  true,
    
    lowercase:  true,
    
    validate(value) {
    
    if (!validator.isEmail(value)) {
    
    throw  new  Error('Email is invalid')
    
    }    
    }    
    },    
    password: {
    
    type:  String,
    
    required:  true,
    
    minlength:  7,
    
    trim:  true,
    
    validate(value) {    
    if (value.toLowerCase().includes('password')) {    
    throw  new  Error('Password cannot contain "password"')    
    }    
    }    
    },age: {    
    type:  Number,    
    default:  0,    
    validate(value) {    
    if (value  <  0) {    
    throw  new  Error('Age must be a postive number')    
    }    
    }    
    }    
    })       
    
    module.exports  =  User
    

    【讨论】:

    • 在回答旧帖子时,如果您可以为您的回答提供一些上下文而不仅仅是代码,这将很有帮助,因为它可能对其他人更有用。
    【解决方案3】:

    我遇到了。我解决了。

    const UserModel = require('../models/userModel')
    
    exports.getUser  =  async(req, res) => {
    
    const  _id  =  req.params.id
    
    try {
    
    const  user  =  await  UserModel.findById(_id)
    
    if (!user) {
    
    return  res.status(404).send()
    
    }
    
    res.status(201).send(user)
    
    
    
    } catch (error) 
    {
    
    res.status(500).send(error)    
    
    }    
    }
    

    控制器/路由

    router.get('/user/:id', userController.getUser)

    【讨论】:

      【解决方案4】:

      使用Article.findById(mongoose.Types.ObjectId(req.params.id)}, (err, article)...

      当您在寻找对象 id 而不是字符串时。

      【讨论】:

      • 我这样做了,我得到了以下信息:Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters 所以我去检查了数据库,因为我怀疑可能没有为 id 存储值,这就是为什么它不会显示它,但是当我检查 id 时,它就在那里,所以我又回到了第一格
      • 难道req.params.id不存在?
      • 好吧,我可以记录req.params.id ,它会返回正确的值
      • 好吧,我发现我加载了错误的参数,这就是它找不到 id 的原因,我给了它 article_id 的参数,应该是 article._id
      • 所以我可以使用Article.find 获取值,但是当我尝试使用Article.findById 时,我又得到了一个未定义的值 O.o"
      猜你喜欢
      • 2019-02-08
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      相关资源
      最近更新 更多