具有引用数组的Mongoose模型模式:CastError:对于值"[object Object]",Cast to ObjectId失败

Rac*_*ace 11 mongoose mongodb node.js express mean-stack

我用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' }
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我吗?相关代码如下:

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);
Run Code Online (Sandbox Code Playgroud)

Category模型定义如下:

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

当我创建一篇新文章并将其保存为:

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);
  });
};
Run Code Online (Sandbox Code Playgroud)

调用该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' }
Run Code Online (Sandbox Code Playgroud)

我google了很多,但没有运气.请帮我!


更新: 感谢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);

  });
};
Run Code Online (Sandbox Code Playgroud)

输出如下:

// 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 (??????) 
}
Run Code Online (Sandbox Code Playgroud)

这没问题.

Ger*_*osi 19

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

var ArticleSchema = new Schema({
  ...
  categories: [{ 
    type: Schema.ObjectId, 
    ref: 'Category' }]
});
Run Code Online (Sandbox Code Playgroud)

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

categories:
   [ { _id: '53c934bbf299ab241a6e0524',
     name: '1111',
     parent: '53c934b5f299ab241a6e0523',
     __v: 0,
     subs: [],
     sort: 1 } ]
Run Code Online (Sandbox Code Playgroud)

并且Mongoose无法将类别对象转换为ObjectId.这就是你得到错误的原因.确保categoriesreq.body只包含IDS:

{ title: 'This is title',
  content: '<p>content here</p>',
  categories: [ '53c934bbf299ab241a6e0524' ],
  updated: [ 1405697477413 ] }
Run Code Online (Sandbox Code Playgroud)


Jan*_*ana 9

请使用mongoose.Schema.Types.Mixed作为类别的数据类型.我在保存数据数组时遇到了同样的问题.这个对我有用.

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.Types.Mixed }]
});
mongoose.model('Article', ArticleSchema);
Run Code Online (Sandbox Code Playgroud)