保存Mongoose中的自增ID/计数器

huangapple go评论66阅读模式
英文:

Save auto incrementing id / counter in Mongoose

问题

以下是您要翻译的内容:

Is there a way to set the id (or a counter) in the pre or post save middleware?

I'd like to have a running auto increment that stores the latest index of a document.
In my case whenever I save a new page (no update!), I need the id (or a counter) to start with 0 and increasing with each new page.

I've tried both pre and post middlewares in which I set the id and also the _id directly to the number of existing pages. However, Mongoose preserves its automatically generated id and doesn't allow it to be overwritten.

Also I'm not able to set the value to a field like 'counter' in the pre or post middleware.
Obviously, I'm doing something totally wrong.

Sadly the mongoose documentation does not provide any enlightening example.
Please help.

(Side note: I don't want to update the id/counter manually in a following update. Neither do I want the client code to provide a counter variable. The save logic needs to figure this out on its own.)

import mongoose from 'mongoose'
import { updateIfCurrentPlugin } from 'mongoose-update-if-current'

interface PageDoc extends mongoose.Page {
    counter: number
    name: string

// An interface that describes the properties that are required to create a new Page.
interface PageAttrs {
    name: string
}

interface PageModel extends mongoose.Model<PageDoc> {
    build(attrs: PageAttrs): PageDoc
}

const PageSchema = new mongoose.Schema<PageDoc>(
    {
        name: {
            type: String,
            required: true
        }
    },
    {
        toJSON: {
            transform(doc, ret) {
                // modify ret directly
                ret.id = ret._id
                delete ret._id
                //delete ret.__v //versionKey: false,
            }
        }
    }
)

PageSchema.pre('save', async function (next) {
    const existingPages = await Page.find({})

    this.set('id', existingPages.length)
    next()
})

PageSchema.set('versionKey', 'version')
PageSchema.plugin(updateIfCurrentPlugin)

PageSchema.statics.build = (attrs: PageAttrs) => {
    //const existingPages = await Page.find({})

    let symbol = new Page({
        name: attrs.name
    })

    console.log('Returning page with id ', symbol.id)

    return symbol
}

const Page = mongoose.model<PageDoc, PageModel>('Page', PageSchema)

export { Page }
英文:

Is there a way to set the id (or a counter) in the pre or post save middleware?

I'd like to have a running auto increment that stores the latest index of a document.
In my case whenever I save a new page (no update!), I need the id (or a counter) to start with 0 and increasing with each new page.

I've tried both pre and post middlewares in which I set the id and also the _id directly to the number of existing pages. However, Mongoose preserves its automatically generated id and doesn't allow it to be overwritten.

Also I'm not able to set the value to a field like 'counter' in the pre or post middleware.
Obviously, I'm doing something totally wrong.

Sadly the mongoose documentation does not provide any enlightening example.
Please help.

(Side note: I don't want to update the id/counter manually in a following update. Neither do I want the client code to provide a counter variable. The save logic needs to figure this out on its own.)

import mongoose from &#39;mongoose&#39;
import { updateIfCurrentPlugin } from &#39;mongoose-update-if-current&#39;

interface PageDoc extends mongoose.Page {
	counter: number
	name: string

// An interface that describes the properties that are required to create a new Page.
interface PageAttrs {
	name: string
}

interface PageModel extends mongoose.Model&lt;PageDoc&gt; {
	build(attrs: PageAttrs): PageDoc
}

const PageSchema = new mongoose.Schema&lt;PageDoc&gt;(
	{
		name: {
			type: String,
			required: true
		}
	},
	{
		toJSON: {
			transform(doc, ret) {
				// modify ret directly
				ret.id = ret._id
				delete ret._id
				//delete ret.__v //versionKey: false,
			}
		}
	}
)

PageSchema.pre(&#39;save&#39;, async function (next) {
	const existingPages = await Page.find({})

	this.set(&#39;id&#39;, existingPages.length)
	next()
})

PageSchema.set(&#39;versionKey&#39;, &#39;version&#39;)
PageSchema.plugin(updateIfCurrentPlugin)

PageSchema.statics.build = (attrs: PageAttrs) =&gt; {
	//const existingPages = await Page.find({})

	let symbol = new Page({
		name: attrs.name
	})

	console.log(&#39;Returning page with id &#39;, symbol.id)

	return symbol
}

const Page = mongoose.model&lt;PageDoc, PageModel&gt;(&#39;Page&#39;, PageSchema)

export { Page }

答案1

得分: 1

你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。以下是要翻译的内容:

idt you need middleware for it, it will cause issue if some users creating page in the same time

不需要middleware,如果有多个用户同时创建页面,会导致问题。

and keep _id as it is, use counter instead

保留_id不变,使用counter代替。

to count all the documents, use `count()

要计算所有文档的数量,使用count()

the code would be like:

代码会是这样的:

const counter = await Page.countDocuments({});

const data = new Page({
       counter: counter,
       name: attrs.name
    });
await Page.save();
英文:

idt you need middleware for it, it will cause issue if some users creating page in the same time

and keep _id as it is, use counter instead

to count all the documents, use `count()

the code would be like:

const counter = await Page.countDocuments({});
const data = new Page({
counter: counter
name: attrs.name
})
await Page.save()
}

huangapple
  • 本文由 发表于 2023年3月4日 02:18:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定