node.js - mongoose嵌入子文档的问题

查看:138
本文介绍了node.js - mongoose嵌入子文档的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

const EventSchema = new Schema({
    dates: [Number],
    reason: {
        type: String,
        required: true
    },
    userId: Schema.Types.ObjectId,
    type: {
        type: String,
        required: true
    }
});

const CalendarSchema = new Schema({
    date: {
        type: Number,
        index: {
            unique: true
        }
    },
    events: [EventSchema]
});

在mongoose张这样嵌入子文档应该是没问题的吧?可我在插入子文档的时候报错了

.post(({ body }, res, next) => {
    const event = new Event(body);
    event.save()
        .then(savedEvent => {
            let promises = [];
            for (date of body.dates) {
                promises.push(Calendar.update({date}, {
                    $push: savedEvent._doc
                }));
            }
            return Promise.all(promises);
        })
        .then(() => res.end())
        .catch(next);
})

错误:
The field '_id' must be an array but is of type OID in document {_id: ObjectId('57c5a02c8890a02814771df1')}

是我哪里写错了吗?

解决方案

写法是不是不太对啊,文档上是这样用的
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});

这篇关于node.js - mongoose嵌入子文档的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆