根据这篇mongodb文章,可以自动增加一个字段,我想使用计数器收集方式.
这个例子的问题是我没有成千上万的人使用mongo控制台在数据库中键入数据.相反,我试图使用猫鼬.
所以我的架构看起来像这样:
var entitySchema = mongoose.Schema({
testvalue:{type:String,default:function getNextSequence() {
console.log('what is this:',mongoose);//this is mongoose
var ret = db.counters.findAndModify({
query: { _id:'entityId' },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
}
});
Run Code Online (Sandbox Code Playgroud)
我在同一个数据库中创建了计数器集合,并添加了一个_id为'entityId'的页面.从这里我不知道如何使用mongoose更新该页面并获得递增的数字.
计数器没有架构,我希望它保持这种方式,因为这实际上不是应用程序使用的实体.它只应在模式中用于自动增量字段.
我有一个数据库,它由四个字段 id、text、key、status 组成。我想添加另一个名为 order 的字段,它由一个数字组成,它是订单的表示。我也有删除文档的功能,因此删除顺序不会连续,我也希望顺序连续且不重复。如果从数据库中删除了某些文档,则根据数据库中的文档数量自动调整顺序。我有两个文件 index.js 和 items.js。我使用过猫鼬、body-parser 和 expressjs。
我的订单字段是非重复和连续的。
索引.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');
app.use(bodyParser.json());
app.use(cors());
Items = require('./items.js');
mongoose.connect('mongodb://localhost/taskDb');
var db = mongoose.connection;
app.get("/", (req, res) => {
res.send('Visit /api/*****');
});
app.get("/api/items", (req, res) => {
Items.getItems(function (err, items) {
if (err) {
throw err;
}
res.json(items);
});
});
app.post("/api/items", (req, res) => {
var item = req.body;
console.log(item + "item …Run Code Online (Sandbox Code Playgroud) 有人可以指导我如何在将 mongoose 与 NestJS 框架一起使用时自动递增集合内的任何字段。
例如:假设我有这个用户模式
@Schema()
export class User extends Document {
@Prop()
userId: number; // I want to increment this field on each new user
@Prop()
name: string;
@Prop({
type: String,
required: true,
unique: true,
})
email: string;
@Prop()
isEmailVerified: boolean;
@Prop({
type: String,
required: true,
unique: true,
})
mobile: string;
@Prop()
isMobileVerified: boolean;
@Prop({
type: String,
required: true,
})
password: string;
}
export const UserSchema = SchemaFactory.createForClass(User);
Run Code Online (Sandbox Code Playgroud)
我想增加每个新用户的 userId 。谢谢