【问题标题】:Mongoose default field-value in schema seems not to work模式中的猫鼬默认字段值似乎不起作用
【发布时间】:2020-06-23 10:10:59
【问题描述】:

调用 createPost 函数时出错。

错误信息是: 'E11000 重复键错误集合:photogram-db.posts index: likes_1 dup key: { likes: undefined }'

由于喜欢字段的重复值而发生错误,但喜欢字段未设置为唯一({唯一:true}),其次为什么喜欢未定义它应该默认为空数组,最后应该是唯一的值唯一的是 Account 对象在字段 likes 中引用。

在 createPost 函数中调用 post.save() 方法时会引发错误

import {
    Schema,
    model,
    Document
}
from "mongoose";

import { 
    AccountModel,
    IAccountDocument, 
    IAccount
} 
from "./account";

import { 
    createNotification 
} 
from "./notification";

import removeItemInArray, { checkIdFn } from "../utilities/removeItemInArray";

import hasItemInArray from "../utilities/hasItemInArray";
import settings from "../settings";
import { searchModel } from "./searchHelper";



export interface IPost {
    title: String;

    image: Buffer;

    text?: String;
}

export interface IPostInit extends IPost {
    creator: IAccountDocument["_id"]
}

export interface IPostDocument extends IPostInit, Document {
    likes: Array<IAccountDocument["_id"]>;

    dislikes: Array<IAccountDocument["_id"]>;

    createdAt: Date;
};



const {
    Types: {
        String,
        Buffer,
        ObjectId
    }
} = Schema;

const PostSchema = new Schema({
    title: {
        type: String,

        required: true
    },

    text: {
        type: String,

        require: false
    },

    image: {
        type: Buffer,

        require: true
    },



    createdAt: {
        type: Date,

        default: new Date(),

        required: false
    },

    creator: {
        type: ObjectId,

        ref: "Account",

        required: true
    },



    likes: {
        type: [{
            type: ObjectId,

            ref: "Account",

            required: false,

            unique: true
        }],

        default: [],

        required: false
    },

    disLikes: {
        type: [{
            type: ObjectId,

            ref: "Account",

            required: false,

            unique: true
        }],

        default: [],

        required: false
    }
});

PostSchema.index({
    title: "text",
    text: "text"
});

export const createPost = async (settings: IPostInit) => {

    const post = new PostModel(settings);

    post.createdAt = new Date();

    await post.save();

    return post;
} 

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    我犯了一个愚蠢的错误。唯一字段只能用于文档属性,不能用于文档属性内的数组项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2020-09-23
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多