簡體   English   中英

如何更新貓鼬架構?

[英]How to update mongoose schema?

剛開始學習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
        }
    });

這是我閱讀這篇文章后提出的最好的選擇,但是它給我拋出一個錯誤TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays. 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
        }
    }
}); 

您不能使用這樣的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]
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM