【问题标题】:Cast to ObjectID failed for value at path in mongoose猫鼬路径中的值转换为 ObjectID 失败
【发布时间】:2020-02-14 10:19:56
【问题描述】:

我正在创建一个包含 mongoose、node 和 angular 的博客应用程序,其中涉及两个模型模式。一个用于博客,另一个用于类别。创建博客时,从类别模型中获取类别。理想的功能应该是,当用户点击创建博客 api 时,首先会加载一个表单以及一个下拉列表,其中通过获取请求获取现有类别列表,并且每个元素都是类别模型的文档,具有创建的唯一 id shortId、categoryName 以及 mongoose id。在下拉列表中仅获取 categoryName。现在,当用户填写表单并提交时,在节点控制器函数中,类别应该保存 categoryId 而不是 categoryName,这样我以后可以对具有相同 categoryId 的多个博客进行排序。但是在创建博客时,我的类别未定义。但是这样做时它会在控制台上获取错误:类别未定义

博客模型:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let blogSchema = new Schema(
    {
        blogId: {type: String,unique: true,index: true},
        title: {type: String,default: ''},
        category : {type: Schema.Types.ObjectId, ref: 'Category'},
        imagePath: {type: String,default: '' }})
mongoose.model('Blog', blogSchema);

类别模型:

var mongoose = require('mongoose');
const Schema = mongoose.Schema;
var CategorySchema = new Schema(
  {
    categoryId: {
      type: String,unique: true,index: true},
    categoryName: {
      type: String,default: ''
    }})
mongoose.model('Category', CategorySchema);

博客创建控制器功能:

 let createBlog = (req, res) => {

        CategoryModel.findOne({ 'categoryName': req.body.category }, (err, result) => {
            if (err) { console.log('Error at finding categoryId ::', err); res.send(err) }
            /** If db operation is success findOne will return either document or null, we're only projecting _id */
            if (result) {
                console.log('ZZZZZ'+result.categoryId)
                let blogId = shortid.generate()
                let newBlog = new BlogModel({
                    blogId: blogId,
                    title: req.body.title,
                    category: mongoose.Types.ObjectId(result.categoryId), // As result._id will be string needs to convert it to ObjectId()
                    imagePath: req.file.path
                })
                newBlog.save((err, result) => {
                    if (err) { console.log('Error at saving new blog ::', err); res.send(err) }
                    else { console.log('Successfully saved new blog'); res.send(result) }
                })
            } else {
                console.log('No category found for ::', req.body.category)
                res.send('No category found')
            }
        })
    }

【问题讨论】:

  • 似乎您将值 movies 传递给 Blog 模型中的 category 字段,而不是传递有效的 ObjectId(),您需要记录此请求 req.body.category 并检查是什么价值!!
  • 那么我应该如何在博客模型的类别字段中传递 ObjectId()?
  • 你在req.body.category 中得到了什么你想传递给类别字段的内容?
  • 我要拍电影
  • 如果您必须将Movies 存储为category 中的字符串,则将此category : {type: Schema.Types.ObjectId, ref: 'Category'}, 替换为category : {type: String}

标签: node.js mongodb mongoose


【解决方案1】:

从下面的错误:

Cast to ObjectID failed for value "Movies" at path "category" at

这是因为您将字符串 Movies 传递给 Blog 模型的类别字段,该字段实际上是在寻找 ObjectId() 而不是字符串, 由于您需要类别字段的类别ObjectId(),因此您需要首先从类别集合中读取它并将其保存为类别,同时保存新博客。

您的博客创建控制器应如下所示:

var mongoose = require('mongoose');

let createBlog = (req, res) => {
    CategoryModel.findOne({ 'categoryId': req.body.category }, { _id: 1 }, (err, result) => {
        if (err) { console.log('Error at finding categoryId ::', err); res.send(err) }
        /** If db operation is success findOne will return either document or null, we're only projecting _id */
        if (result) {
            let blogId = shortid.generate()
            let newBlog = new BlogModel({
                blogId: blogId,
                title: req.body.title,
                category: mongoose.Types.ObjectId(result._id), // As result._id will be string needs to convert it to ObjectId()
                imagePath: req.file.path
            })
            newBlog.save((err, result) => {
                if (err) { console.log('Error at saving new blog ::', err); res.send(err) }
                else { console.log('Successfully saved new blog'); res.send(result) }
            })
        } else {
            console.log('No category found for ::', req.body.category)
            res.send('No category found')
        }
    })
}

【讨论】:

  • @chatterjeetridib :您是否在 DB 上执行了该查询并检查?
  • 我没找到你
  • @chatterjeetridib:您的意思是您是否使用相同的请求和响应在 Db 上测试了 findOne 查询?似乎在您的代码中它返回null
  • 是的,我做到了,响应在控制台中未定义时未找到任何类别
  • @chatterjeetridib : 你在req.body.category 有什么?您是否打印并检查类型是否匹配?您是否也直接在 Db 上执行并获取响应文档或 null
猜你喜欢
  • 2021-04-21
  • 2017-10-24
  • 2015-11-07
  • 2019-05-02
  • 1970-01-01
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
相关资源
最近更新 更多