添加到新创建的对象的数组

时间:2017-03-06 23:33:38

标签: javascript node.js mongodb mongoose

我使用平均堆栈作为我的应用程序的后端。

要创建新对象,我使用POST。创建该对象后,它会创建另外两个链接在一起的对象。

离。我创建了一个Book对象,在该过程中创建了一个章节和页面对象。页面对象添加到Chapter.pages,而Chapter添加到Book.chapters。好吧,至少那是我正在尝试做的,但我收到了这个错误..

错误:

    Unhandled rejection TypeError: Cannot read property 'push' of undefined
at /Users//Documents/development/mean/lookback/server/api/book/book.controller.js:96:7
    From previous event:
at create (/Users//Documents/development/mean/lookback/server/api/book/book.controller.js:88:6)
at Layer.handle [as handle_request] (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/layer.js:95:5)
at next (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/route.js:131:13)
at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:40:9)
at /Users//Documents/development/mean/lookback/server/auth/auth.service.js:38:11
    From previous event:
at Middleware_Common_Object.<anonymous> (/Users//Documents/development/mean/lookback/server/auth/auth.service.js:33:10)
at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:59:18)
at /Users//Documents/development/mean/lookback/node_modules/express-jwt/lib/index.js:123:7
at /Users//Documents/development/mean/lookback/node_modules/async/lib/async.js:52:16
at Immediate.<anonymous> (/Users//Documents/development/mean/lookback/node_modules/async/lib/async.js:1206:34)
at runCallback (timers.js:637:20)
at tryOnImmediate (timers.js:610:5)
at processImmediate [as _immediateCallback] (timers.js:582:5)

物件 书:

    'use strict';

    import mongoose from 'mongoose';

    var BookSchema = new mongoose.Schema({

    chapters:[{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'chapter'
    }],


    export default mongoose.model('Book', BookSchema);

章:

    'use strict';

    import mongoose from 'mongoose';

    var ChapterSchema = new mongoose.Schema({
      pages: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Page'
      }],
      startDate: {
        type: Date,
        default: Date.now
      },
      endDate: {
        type: Date,
      },
      book:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Book'
      }
    });

    export default mongoose.model('Chapter', ChapterSchema);

页:

    'use strict';

    import mongoose from 'mongoose';

    var PageSchema = new mongoose.Schema({
     posts: [{
       type: mongoose.Schema.Types.ObjectId, 
      ref: 'Post',
     }],
     startDate: {
        type: Date,
        default: Date.now
      },
      endDate: {
        type: Date
      },
      chapter: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Chapter'
      }
    });

    export default mongoose.model('Page', PageSchema);

控制器:

export function create(req, res) {
return Book.create(req.body)
    .then(book => {
      var birthdate = new Date(req.body.birthdate);
      var startDate = new Date(new Date().getFullYear() + 1, birthdate.getMonth(), birthdate.getDate(), 0, 0, 0);
      var endDate = new Date(new Date().getFullYear() + 1, birthdate.getMonth(), birthdate.getDate() - 1, 23, 59, 59);
      var chapter = Chapter.create({"book": book._id, "startDate": startDate, "endDate": endDate, pages: []});
      var date = new Date();
      endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59);
      var page = Page.create({"chapter": chapter._id, "endDate": endDate});
      chapter.pages.push(page._id);

      book.chapters.push(chapter._id);
      book.save()
    .then(respondWithResult(res, 201))
    .catch(handleError(res));
    });
}

我尝试在推送它们之前初始化数组,但这也给了我一个错误..即。 book.chapters = []; chapter.pages = [];

错误:

Unhandled rejection CastError: Cast to ObjectId failed for value "Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _trace: 
   { Error
       at Promise.longStackTracesCaptureStackTrace [as _captureStackTrace] (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/debuggability.js:397:19)
       at Promise._resolveFromExecutor (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:478:10)
       at new Promise (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:77:14)
       at Function.create (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/model.js:1803:17)
       at /Users//Documents/development/mean/lookback/server/api/book/book.controller.js:92:29
       at tryCatcher (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/util.js:16:23)
       at Promise._settlePromiseFromHandler (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:510:31)
       at Promise._settlePromise (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:567:18)
       at Promise._settlePromise0 (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:612:10)
       at Promise._settlePromises (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:691:18)
       at Async._drainQueue (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:133:16)
       at Async._drainQueues (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:143:10)
       at Immediate.Async.drainQueues (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:17:14)
       at runCallback (timers.js:637:20)
       at tryOnImmediate (timers.js:610:5)
       at processImmediate [as _immediateCallback] (timers.js:582:5)
     _parent: 
      { Error
          at Promise.longStackTracesCaptureStackTrace [as _captureStackTrace] (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/debuggability.js:397:19)
          at Promise._then (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:231:17)
          at Promise.then (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:124:17)
          at create (/Users//Documents/development/mean/lookback/server/api/book/book.controller.js:88:6)
          at Layer.handle [as handle_request] (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/layer.js:95:5)
          at next (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/route.js:131:13)
          at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:40:9)
          at /Users//Documents/development/mean/lookback/server/auth/auth.service.js:38:11
          at tryCatcher (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/util.js:16:23)
          at Promise._settlePromiseFromHandler (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:510:31)
          at Promise._settlePromise (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:567:18)
          at Promise._settlePromise0 (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:612:10)
          at Promise._settlePromises (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/promise.js:691:18)
          at Async._drainQueue (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:133:16)
          at Async._drainQueues (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:143:10)
          at Immediate.Async.drainQueues (/Users//Documents/development/mean/lookback/node_modules/bluebird/js/release/async.js:17:14)
          at runCallback (timers.js:637:20)
          at tryOnImmediate (timers.js:610:5)
          at processImmediate [as _immediateCallback] (timers.js:582:5)
        _parent: [Object],
        _promisesCreated: 0,
        _length: 2,
        _promiseCreated: [Circular] },
     _promisesCreated: 0,
     _length: 3,
     _promiseCreated: null },
  pages: 
   [ Promise {
       _bitField: 0,
       _fulfillmentHandler0: undefined,
       _rejectionHandler0: undefined,
       _promise0: undefined,
       _receiver0: undefined,
       _trace: [Object] } ] }" at path "chapters"
       at Function.create (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/model.js:1803:17)
       at /Users//Documents/development/mean/lookback/server/api/book/book.controller.js:92:29
       at runCallback (timers.js:637:20)
       at tryOnImmediate (timers.js:610:5)
       at processImmediate [as _immediateCallback] (timers.js:582:5)
          at create (/Users//Documents/development/mean/lookback/server/api/book/book.controller.js:88:6)
          at Layer.handle [as handle_request] (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/layer.js:95:5)
          at next (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/route.js:131:13)
          at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:40:9)
          at /Users//Documents/development/mean/lookback/server/auth/auth.service.js:38:11
          at runCallback (timers.js:637:20)
          at tryOnImmediate (timers.js:610:5)
          at processImmediate [as _immediateCallback] (timers.js:582:5)
    at MongooseError.CastError (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/error/cast.js:26:11)
    at ObjectId.cast (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/schema/objectid.js:147:13)
    at Array._cast (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/types/array.js:125:32)
    at Array._mapCast (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/types/array.js:296:17)
    at Object.map (native)
    at Array.push (/Users//Documents/development/mean/lookback/node_modules/mongoose/lib/types/array.js:309:25)
    at /Users//Documents/development/mean/lookback/server/api/book/book.controller.js:99:21
From previous event:
    at create (/Users//Documents/development/mean/lookback/server/api/book/book.controller.js:88:6)
    at Layer.handle [as handle_request] (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users//Documents/development/mean/lookback/node_modules/express/lib/router/route.js:131:13)
    at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:40:9)
    at /Users//Documents/development/mean/lookback/server/auth/auth.service.js:38:11
From previous event:
    at Middleware_Common_Object.<anonymous> (/Users//Documents/development/mean/lookback/server/auth/auth.service.js:33:10)
    at next (/Users//Documents/development/mean/lookback/node_modules/composable-middleware/lib/composable-middleware.js:59:18)
    at /Users//Documents/development/mean/lookback/node_modules/express-jwt/lib/index.js:123:7
    at /Users//Documents/development/mean/lookback/node_modules/async/lib/async.js:52:16
    at Immediate.<anonymous> (/Users//Documents/development/mean/lookback/node_modules/async/lib/async.js:1206:34)
    at runCallback (timers.js:637:20)
    at tryOnImmediate (timers.js:610:5)
    at processImmediate [as _immediateCallback] (timers.js:582:5)

1 个答案:

答案 0 :(得分:0)

你几乎拥有它。您需要做的是推送实际的对象ID而不是对象本身。

chapter.pages.push(页); to chapter.pages.push(mongoose.Types.ObjectId(page._id));

book.chapters.push(章); to book.chapters.push(mongoose.Types.ObjectId(chapter._id));

export function create(req, res) {
  return Book.create(req.body)
    .then(book => {
      var birthdate = new Date(req.body.birthdate);
      var startDate = new Date(new Date().getFullYear() + 1, birthdate.getMonth(), birthdate.getDate(), 0, 0, 0);
      var endDate = new Date(new Date().getFullYear() + 1, birthdate.getMonth(), birthdate.getDate() - 1, 23, 59, 59);
      var chapter = Chapter.create({"book": book, "startDate": startDate, "endDate": endDate, pages: []});
      var date = new Date();
      endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59);
      var page = Page.create({"chapter": chapter, "endDate": endDate});
      chapter.pages.push(mongoose.Types.ObjectId(page._id));
      book.chapters.push(mongoose.Types.ObjectId(chapter._id));
      book.save()
    .then(respondWithResult(res, 201))
    .catch(handleError(res));
    });
}