我想使用环回自动增加mongodb文档编号。
我在mongo中创建了函数
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
db.tweet.insert(
{
"_id" : getNextSequence("userid"),
"content": "test",
"date": "1",
"ownerUsername": "1",
"ownerId": "1"
}
)
它在mongo shell中工作。
但是当我使用loopback.js浏览器(http://localhost:3000/explorer/)插入时,它无效。 显示400错误(SytaxError)代码。
我不能在loopback rest API中使用mongo函数吗?
我认为问题是此行中的引号 getNextSequence(“userid”),
答案 0 :(得分:3)
使用属性counters
和value
collection
{
"name": "counters",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"type": "number",
"collection": "string"
},
"validations": [],
"relations": {},
"acls": [
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}
],
"methods": []
}
现在假设您的自动增量集合名称为tweets
。
将此值插入counters
。
{
"value" : 0,
"collection" : "tweet"
}
现在常见/ models / tweet.js
tweet.observe('before save', function (ctx, next) {
var app = ctx.Model.app;
//Apply this hooks for save operation only..
if(ctx.isNewInstance){
//suppose my datasource name is mongodb
var mongoDb = app.dataSources.mongodb;
var mongoConnector = app.dataSources.mongodb.connector;
mongoConnector.collection("counters").findAndModify({collection: 'tweet'}, [['_id','asc']], {$inc: { value: 1 }}, {new: true}, function(err, sequence) {
if(err) {
throw err;
} else {
// Do what I need to do with new incremented value sequence.value
//Save the tweet id with autoincrement..
ctx.instance.id = sequence.value.value;
next();
} //else
});
} //ctx.isNewInstance
else{
next();
}
}); //Observe before save..
答案 1 :(得分:1)
我想再向Robins Answer添加1点,你可以添加upsert:true,以便在文档不存在的情况下自动创建文档
tweet.observe('before save', function (ctx, next) {
var app = ctx.Model.app;
//Apply this hooks for save operation only..
if(ctx.isNewInstance){
//suppose my datasource name is mongodb
var mongoDb = app.dataSources.mongodb;
var mongoConnector = app.dataSources.mongodb.connector;
mongoConnector.collection("counters").findAndModify({collection: 'tweet'}, [['_id','asc']], {$inc: { value: 1 }}, {new: true,upsert:true}, function(err, sequence) {
if(err) {
throw err;
} else {
// Do what I need to do with new incremented value sequence.value
//Save the tweet id with autoincrement..
ctx.instance.id = sequence.value.value;
next();
} //else
});
} //ctx.isNewInstance
else{
next();
}
}); //Observe before save..
答案 2 :(得分:1)
您可以在此示例中为回送4做类似的事情
let last_record = await this.testRepository.findOne({order: ['id DESC']});
if(last_record) invoice.id = last_record.id+1;
这将使用以下属性生成您的模型:
@property({
type: 'number',
id: true,
default: 1,
generated: false
})
id: number;
希望这会有所帮助,如果还有其他代码,请给我写信。谢谢
答案 3 :(得分:0)
如果您想在回送方法中直接使用 MongoDB 运算符,您需要启用选项“allowExtendedOperators”,您可以在每个模型的基础上或在数据源级别执行此操作(将适用于使用数据源的所有模型) .
数据源.json:
"MongoDs": {
"host": "127.0.0.1",
"port": 27017,
"url": "mongodb://localUser:MYPASSWORD!@127.0.0.1:27017/test-database",
"database": "test-database",
"password": "MYPASSWORD!",
"name": "MongoDs",
"user": "localUser",
"useNewUrlParser": true,
"connector": "mongodb",
"allowExtendedOperators": true
},