猫鼬路径上的值强制转换为ObjectID

时间:2020-02-11 01:12:45

标签: node.js mongodb mongoose

我正在创建一个包含mongoose,node和angular的博客应用程序,其中涉及两个模型架构。一种用于博客,另一种用于类别。创建博客后,将从类别模型中获取类别。理想的功能应该是,当用户点击create blog api时,首先会加载一个表单以及一个下拉菜单,其中通过get请求获取现有的类别列表,并且每个元素都是具有唯一ID的类别模型文档。 shortId,categoryName以及猫鼬ID。在下拉列表中,仅会提取categoryName。现在,当用户填写表单并提交表单时,在节点控制器功能中,类别应该不按categoryName保存categoryId,这样我以后就可以对具有相同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')
            }
        })
    }

1 个答案:

答案 0 :(得分:0)

以下错误:

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

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

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

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