草庐IT

node.js - 引用数组 : CastError: Cast to ObjectId failed for value "[object Object]" 的 Mongoose 模型架构

coder 2023-05-04 原文

我用 express.js 和 mongoosejs 构建了一个博客网站。一篇文章可能有一个或多个类别。创建新文章时出现错误:

{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "categories"]
  message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"',
  name: 'CastError',
  type: 'ObjectId',
  value: [ [object Object] ],
  path: 'categories' }

谁能帮帮我? 相关代码如下:

Article 模型定义如下:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
created: {  type: Date, default: Date.now},
title: String,
content: String,
summary: String,
categories: [{ 
    type: Schema.ObjectId, 
    ref: 'Category' }]
});
mongoose.model('Article', ArticleSchema);

Category 模型定义如下:

var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CategorySchema = new Schema({
  parent: {
    type: Schema.ObjectId,
  },
  name: String,
  subs: [CategorySchema]
});
mongoose.model('Category', CategorySchema);

当我创建一个新文章并像这样保存它时:

exports.create = function(req, res) {
  console.log(req.body);
  var article = new Article(req.body);
  article.user = req.user;
  console.log(article);
  article.save(function(err) {
    if (err) {
        console.log(err);
        return res.jsonp(500, {
            error: 'Cannot save the article'
        });
    }
    res.jsonp(article);
  });
};

调用 create 函数时,console.log() 输出如下所示:

// console.log(req.body);
{ title: 'This is title',
  content: '<p>content here</p>',
  categories:
   [ { _id: '53c934bbf299ab241a6e0524',
     name: '1111',
     parent: '53c934b5f299ab241a6e0523',
     __v: 0,
     subs: [],
     sort: 1 } ],
  updated: [ 1405697477413 ] }

// console.log(article);
{ 
  title: 'This is title',
  content: '<p>content here</p>',
  _id: 53c93dc5b1c3b8e80cb4936b,
  categories: [],
  created: Fri Jul 18 2014 23:31:17 GMT+0800 (中国标准时间) }

// console.log(err);
{ [CastError: Cast to ObjectId failed for value "[object Object]" at path "categories"]
  message: 'Cast to ObjectId failed for value "[object Object]" at path "categories"',
  name: 'CastError',
  type: 'ObjectId',
  value: [ [object Object] ],
  path: 'categories' }

我用谷歌搜索了很多,但没有运气。请帮帮我!


更新: 感谢 Gergo 的回答。 但是,如果我用 almoset 相同的代码更新现有文章,它可以正常工作!为什么?代码如下:

var mongoose = require('mongoose'),
    Category = mongoose.model('Category'),
    _ = require('lodash');

exports.update = function(req, res) {
console.log(req.body);
var article = req.article;
article = _.extend(article, req.body);
console.log(article);
article.save(function(err) {
    if (err) {
        return res.jsonp(500, {
            error: 'Cannot update the article'
        });
    }
    res.jsonp(article);

  });
};

输出如下:

// console.log(req.body);
{ _id: '53ca42f418bfb23c1e04df02',
    summary: 'tttt',
    title: 'tt',
    content: '<p>tttt</p>',
    __v: 2,
    categories: [ { _id: '53c934bbf299ab241a6e0524', name: '1111' } ],
    created: '2014-07-19T10:05:40.183Z'
}

// console.log(article);
{ _id: 53ca42f418bfb23c1e04df02,
    title: 'tt',
    content: '<p>tttt</p>',
    __v: 2,
    categories: [ { _id: 53c934bbf299ab241a6e0524, name: '1111', subs: [], sort: 0
    } ],
    created: Sat Jul 19 2014 18:05:40 GMT+0800 (中国标准时间) 
}

这没问题。

最佳答案

您的文章架构需要一个 ObjectId 数组:

var ArticleSchema = new Schema({
  ...
  categories: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Category' }]
});

但是 req.body 包含一个类别对象:

categories:
   [ { _id: '53c934bbf299ab241a6e0524',
     name: '1111',
     parent: '53c934b5f299ab241a6e0523',
     __v: 0,
     subs: [],
     sort: 1 } ]

Mongoose 无法将类别对象转换为 ObjectId。这就是您收到错误的原因。确保 req.body 中的 categories 只包含 id:

{ title: 'This is title',
  content: '<p>content here</p>',
  categories: [ '53c934bbf299ab241a6e0524' ],
  updated: [ 1405697477413 ] }

关于node.js - 引用数组 : CastError: Cast to ObjectId failed for value "[object Object]" 的 Mongoose 模型架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24829355/

有关node.js - 引用数组 : CastError: Cast to ObjectId failed for value "[object Object]" 的 Mongoose 模型架构的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  5. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  6. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  7. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  8. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  9. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  10. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

随机推荐