【问题标题】:Mongodb - Create entry to a extisting collection field arrayMongodb - 创建现有集合字段数组的条目
【发布时间】:2019-07-21 22:45:25
【问题描述】:

所以我对我的var array 添加新章节有疑问,我将如何处理我必须这样做:

array.push({
            chapter: [
                {
                    id: 2,
                    title: 'adsf',
                    content: '',
                    authorNotes: 'asdf'
                }
            ]
        });

RiTest.ts

import * as mongoose from 'mongoose';

const Scheme = mongoose.Schema;

export const RiTestScheme = new Scheme({
    novelName: String,
    novelAuthor: String,
    novelCoverArt: String,
    novelTags: Array,
    chapters: [
        {
            id: Number,
            title: String,
            content: String,
            authorNotes: String
        }
    ]
});

export class RiTestController {
    public addChapter(callback: (data) => void) {
        var chapterInfoModel = mongoose.model('ChaptersTest', RiTestScheme);

        var array = [
        {
            chapter: [
                {
                    id: 0,
                    title: 'prolog',
                    content: 'conetntt is empty',
                    authorNotes: 'nothing is said by author'
                },
                {
                    id: 1,
                    title: 'making a sword',
                    content: 'mine craft end chapter',
                    authorNotes: 'nothing'
                }
            ]
        }
    ];

        let newChapterInfo = new chapterInfoModel(array);

        newChapterInfo.save((err, book) => {
            if (err) {
                return callback(err);
            } else if (!err) {
                return callback(book);
            }
        });
    }
}

这不起作用,var array 没有保存到let newChapterInfo = new chapterInfoModel(array); 我正在尝试做的事情添加另一章到array.chapter 但数组在chapterInfoModel() 中没有得到识别我该怎么办修复此数组并向数组中添加一个项目以在此现有集合中创建一个新条目

感谢您抽出宝贵时间回答我的问题。

【问题讨论】:

    标签: arrays node.js mongodb typescript


    【解决方案1】:

    您正在尝试将文档数组插入到您的集合中,这就是它没有插入到您的集合中的原因。

    Document.prototype.save() 将仅向您的集合中插入一个文档,具体取决于您的定义。所以在这里插入chapter是下面的代码,

    //array as Object
    var array = {
        chapter: [
            {
                id: 0,
                title: 'prolog',
                content: 'conetntt is empty',
                authorNotes: 'nothing is said by author'
            },
            {
                id: 1,
                title: 'making a sword',
                content: 'mine craft end chapter',
                authorNotes: 'nothing'
            }
        ]
    };
    
    //Push to your chapter array
    array.chapter.push({
        id: 2,
        title: 'adsf',
        content: '',
        authorNotes: 'asdf'
    });
    
    let newChapterInfo = new chapterInfoModel(array);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 2020-05-09
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      相关资源
      最近更新 更多