无法将子文档推送到Mongoose中的文档数组

时间:2015-07-11 20:32:47

标签: node.js mongodb mongoose

我正在尝试将一堆子文档推送到文档的数组中。我做错了什么?

错误和代码如下。

错误:

21:28:49 web.1  | { [CastError: Cast to undefined failed for value "{ url: 'http://www.bbc.co.uk',
21:28:49 web.1  |   _id: 55a17c812424c54413de3332,
21:28:49 web.1  |   entities: [],
21:28:49 web.1  |   terms: [] },{ url: 'http://www.google.com',
21:28:49 web.1  |   _id: 55a17c812424c54413de3333,
21:28:49 web.1  |   entities: [],
21:28:49 web.1  |   terms: [] }" at path "documents"]
21:28:49 web.1  |   stack: 'Error\n    at MongooseError.CastError (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/error/cast.js:18:16)\n    at SchemaArray.cast (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/schema/array.js:157:15)\n    at Query._castUpdateVal (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/query.js:2270:22)\n    at Query._walkUpdatePath (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/query.js:2240:25)\n    at Query._castUpdate (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/query.js:2118:23)\n    at Query.update (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/query.js:1959:22)\n    at Function.update (/Users/martynas/Desktop/sandbox/osint-api/node_modules/mongoose/lib/model.js:1734:13)\n    at exports.populateCase (/Users/martynas/Desktop/sandbox/osint-api/app/controllers/case.js:69:10)\n    at Layer.handle [as handle_request] (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/layer.js:82:5)\n    at next (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/route.js:100:13)\n    at Route.dispatch (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/route.js:81:3)\n    at Layer.handle [as handle_request] (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/layer.js:82:5)\n    at /Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/index.js:234:24\n    at param (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/index.js:331:14)\n    at param (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/index.js:347:14)\n    at Function.proto.process_params (/Users/martynas/Desktop/sandbox/osint-api/node_modules/express/lib/router/index.js:391:3)',
21:28:49 web.1  |   message: 'Cast to undefined failed for value "{ url: \'http://www.bbc.co.uk\',\n  _id: 55a17c812424c54413de3332,\n  entities: [],\n  terms: [] },{ url: \'http://www.google.com\',\n  _id: 55a17c812424c54413de3333,\n  entities: [],\n  terms: [] }" at path "documents"',
21:28:49 web.1  |   name: 'CastError',
21:28:49 web.1  |   kind: undefined,
21:28:49 web.1  |   value: [{"url":"http://www.bbc.co.uk","_id":"55a17c812424c54413de3332","entities":[],"terms":[]},{"url":"http://www.google.com","_id":"55a17c812424c54413de3333","entities":[],"terms":[]}],
21:28:49 web.1  |   path: 'documents' }

案例:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var Document = require('./document');

var CaseSchema = ({
    documents: [Document]
});

module.exports = mongoose.model('Case', CaseSchema);

文件:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var DocumentSchema = ({
    url: String
});

module.exports = mongoose.model('Document', DocumentSchema);

代码:

'use strict';

var mongoose = require('mongoose');
var Case = mongoose.model('Case');
var Document = mongoose.model('Document');

exports.populateCase = function(req, res) {

    var caseId = req.params.caseId;

    var doc1 = new Document({
        url: 'http://www.bbc.co.uk'
    });
    var doc2 = new Document({
        url: 'http://www.google.com'
    });

    Case.update({_id: caseId}, {$pushAll: { documents: [doc1, doc2] }}, {upsert: true}, function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log('YAY!');
        }
    });
};

3 个答案:

答案 0 :(得分:2)

子文档需要是mongoose Schema,而不是mongoose Model。您需要指定

var CaseSchema = ({
    documents: [Document.DocumentSchema]
});

或者,您可以将DocumentSchema变量声明放在case.js文件中,然后使用

var CaseSchema = ({
    documents: [DocumentSchema]
});

另外,将case.js文件中的Document声明更改为

var Document = mongoose.model('Document');

根据您加载所有模型文件的方式,您可能需要添加代码

require('./document.js');
require('./code.js');

答案 1 :(得分:2)

您可以尝试这种方式:

<强>案例

var mongoose = require('mongoose'),
    Schema = mongoose.Schema
var CaseSchema = ({
  documents: [{type: Schema.Types.Object, ref: 'Document' }]
});

var Case = mongoose.model('Case', CaseSchema);
module.exports = Case

<强>文档

var mongoose = require('mongoose'),
    Schema = mongoose.Schema

var DocumentSchema = ({
    url: String
});

module.exports = mongoose.model('Document', DocumentSchema);

应用

var Document = require('./Document')
var Case = require('./Case')

var doc1 = new Document({
    url: 'http://www.bbc.co.uk'
});
var doc2 = new Document({
    url: 'http://www.google.com'
});


Case.update({_id: caseId}, {$pushAll: { documents: [doc1, doc2] }}, {upsert: true}, function(err) {
    if (err) {
        console.log(err);
    } else {
        console.log('YAY!');
    }
});

答案 2 :(得分:0)

我已经禁用&#34; _id&#34;字段和添加的自定义&#34; _id&#34;字段&#34;字符串&#34;在案例模型。在我的解决方案中,它使用旧模板中的db_manager(您不需要它)来连接数据库(您可以使用默认模板)。

<强>案例:

var mongoose = require('mongoose');
var Document = require('./document');
var dbManager = require('./../configuration/db_manager.js');
var Schema = mongoose.Schema;

var CaseSchema = new Schema({
  _id: String,
  documents: [Document.schema]
}, {
  _id: false
});

exports.schema = CaseSchema;
exports.model = dbManager.appConnection.model('Case', CaseSchema);

<强>文件:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var dbManager = require('./../configuration/db_manager.js');

var DocumentSchema = new Schema({
  url: String
});

exports.model = dbManager.appConnection.model('Document', DocumentSchema);
exports.schema = DocumentSchema;

<强>代码

exports.populateCase = function(req, res) {
  var caseId = req.params.caseId;

  var doc1 = new documentDbModel.model({
      url: 'http://www.bbc.co.uk'
  });

  var doc2 = new documentDbModel.model({
      url: 'http://www.google.com'
  });

  var docs = [doc1, doc2];

  caseDbModel.model.update({
    "_id": caseId
  }, {
    "$pushAll": {
      "documents": docs
    }
  }, {
    "upsert": true
  }, function(err) {
    if (err) {
      console.log(err);
    } else {
      console.log('YAY!');
    }
  });
};