簡體   English   中英

Mongoose 中的自增字段

[英]Auto-increment field in Mongoose

我正在嘗試使用 Mongoose 創建一個 API,我有一個模型,我想在其中自動增加 postID 的值。 我有帖子模式

const PostSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    postID: {
        type: Number,
        unique: true,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    author: {
        type: Schema.Types.ObjectId,
        ref: 'Author',
        required: true
    },
    dateCreated: {
      type: Date,
      required: true
    },
    lastModified: {
        type: Date,
        required: false
    },
    modifiedBy: {
        type: Schema.Types.ObjectId,
        ref: 'Author',
        required: false
    },
    picture: {
        type: mongoose.SchemaTypes.Url,
        required: false
    }
}, {collection: 'Post'});

我創建了一個預先保存的鈎子

export const PostModel =  mongoose.model('Post', PostSchema);

PostSchema.pre('save', true, async function (next) {
    const post = this;
    post._id = new ObjectID();
    post.dateCreated = new Date();
    try {
        const lastPost = await PostModel.find({postID: {$exists: true}}).sort({id: -1}).limit(1);
        post.postID = lastPost.postID + 1;
    } catch (e){
        console.log('could not take the last post')
    }
    if(post && post.hasOwnProperty('body') && !post.body.isModified){
        return next();
    }
    if(post && post.hasOwnProperty('body') && post.body.isModified){
        post.lastModified = new Date();
        return next();
    }
});

處理添加創建日期,並自動增加 postID。 但是,每當我向 API 發送更改以創建新帖子時,我都會收到一個錯誤: Post validation failed: dateCreated: Path dateCreated is required., id: Path id is required. 這意味着 pre-save hook 中處理的任何工作都沒有完成。 每當我向解析器添加一些隨機值時,突變就會成功完成。 知道為什么預存不起作用嗎?

這是我的解析器

module.exports.addPost = async(_,args, req) => {
    const post = new PostModel({
        title: args.post.title,
        body: args.post.body,
        author: new ObjectID(args.post.author),
        picture: args.post.picture
    });
    try {
        return await post.save();
    } catch (e) {
        console.log('Could not save the post');
        console.log(e);
    }
};

這里的突變

curl 'http://localhost:3001/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:3001' --data-binary '{"query":"mutation($post: PostInput){\n  addPost(post: $post){\n    title\n    body\n    author\n  }\n}","variables":{"post":{"title":"newTitle","body":"Lorem ipsum","author":"5e07e6c07156cb000092ab45","picture":"http://www.example.com"}}}' --compressed

上面的代碼段將不起作用。 根據 Mongoose 的文檔,在編譯模型后調用 pre 或 post 鈎子不起作用。 所以你應該搬家

export const PostModel =  mongoose.model('Post', PostSchema);

低於預鈎。 此外,由於PostModel尚未定義,並且您想要獲取插入到數據庫中的對象的最后一個 id,您可以將此檢查移至您的解析器。

   let lastPost = await PostModel.find({id: {$exists: true}}).sort({id: -1}).limit(1); 
    // This always returns an array, either empty or with data
    if(Array.isArray(lastPost) && lastPost.length > 0){
        lastPost = lastPost[0]
    }
    const post = new PostModel({
        ...
        id: lastPost['id'] + 1
        ...
    });
    if(Array.isArray(lastPost) && lastPost.length === 0) {
        post.id = 0;
    // If this lastPost is an empty array and you try to access the id property
    // you will get an error that NaN to Int conversion failed
    }

希望這可以幫助

暫無
暫無

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

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