如何更新mongoose架构?

时间:2017-03-31 06:25:06

标签: node.js mongodb

刚开始学习mongodb,目前我有这个架构

var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
    type: Date,
    default: Date.now
}});

我想将它更新为这样,但是目前它还没有正常工作,当我在mongo控制台上检查时,架构仍旧是旧的

var BlogSchema = new mongoose.Schema({
        title: String,
        image: String,
        body: String,
        created: {
            type: Date,
            default: Date.now
        },
        author: {
            id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User"
            },
            username: String
        }
    });

这是我在阅读this帖子后提出的最佳信息,但它给我一个错误TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays.

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: {
           type: String,
           required: true, 
           default: null
        }
    }
}); 

1 个答案:

答案 0 :(得分:0)

你不能像那样使用Schema而只是制作另一个authorSchema并将其用作数组。

var mongoose = require('mongoose');

var authorSchema = new mongoose.Schema({
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    username: {
        type: String,
        required: true,
    }
})

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: [authorSchema]
})