在节点中使用计数器集合.js递增 ID 字段
Use counter collection in node.js to increment ID field
我想在我的一个集合上设置一个自动递增的 ID(_id太长了)。为此,我按照包括Mongos官方网站(下图)在内的许多帖子中的建议创建了一个"计数器"集合:
var mongoose = require('mongoose');
module.exports = mongoose.model('Counter', {
_id: String,
sequence_value: Number
});
然后我插入了一个带有 seq 值的计数器。下面是创建新项时调用的函数。添加新项的逻辑有效,获取计数器值的查询在console.log(data.sequence_value);
返回sequence_value的范围内工作。
但是,我无法通过执行以下操作将sequence_value应用于项目创建逻辑:
module.exports.newitem = function(req, res){
var nextId = Counter.findByIdAndUpdate(
{_id: 'productid'},
{ $inc: { incr: 1 } },
function (err, data) {
if(err){
console.log(err.stack || err.message)
} else{
console.log("successful")
}
console.log(data.sequence_value);
return data.sequence_value
});
var item = new Item();
item.itemId = nextId;
// Save the item that has been sent.
item.save();
// If adding the user is successful. Send back the user.
res.json(req.body);
};
逻辑的当前脱节版本如下:
module.exports.newitem = function(req, res){
Counter.findByIdAndUpdate(
{_id: 'productid'},
{ $inc: { incr: 1 } },
function (err, data) {
if(err){
console.log(err.stack || err.message)
} else{
console.log("successful")
}
console.log(data.sequence_value);
});
var item = new Item();
item.itemId = "2000";
// Save the item that has been sent.
item.save();
// If adding the user is successful. Send back the user.
res.json(req.body);
};
希望以上是有道理的。任何帮助都非常感谢。
findByIdAndUpdate
是一个异步函数。 您应该将依赖于其回调的逻辑放在回调本身中,如下所示:
var nextId = Counter.findByIdAndUpdate(
{_id: 'productid'},
{ $inc: { incr: 1 } },
function (err, data) {
if(err){
console.log(err.stack || err.message)
} else{
console.log("successful")
}
console.log(data.sequence_value);
var item = new Item();
item.itemId = data.sequence_value;
// Save the item that has been sent.
item.save(); // arguably, your response would come in the .save() callback, if you care about whether that was successful or not.
// If adding the user is successful. Send back the user.
res.json(req.body);
});
};
以为我会用保罗的答案来表达我最终得到的东西。
module.exports.newitem = function(req, res){
Counter.findByIdAndUpdate(
{_id: 'productid'},
{ $inc: { sequence_value: 1 } },
{ "upsert": true },
function (err, data) {
if(err){
console.log(err.stack || err.message)
} else{
var item = new Item();
item.itemId = data.sequence_value;
...
// Save the item that has been sent.
item.save();
// If adding the user is successful. Send back the user.
res.json(req.body);
console.log("successful")
}
});
};
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 使用agility.js进行页面布局和合成
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 强制模板刷新ember.js
- 如何编写HTML输入的JS内联
- 如何使用以 js 为单位递增的字符串创建 for 循环变量
- Angular JS 自动递增计数器的 ID 字段
- 如何将递增的 for 循环变量传递给 node.js 中的函数
- 自动递增 JS 对象数组
- 在节点中使用计数器集合.js递增 ID 字段
- 数组递增 Javascript / node js / mongodb.
- 在 js 中从数组中的零递增
- JS-阻止数字递增
- 会话变量递增/递减,js函数中的会话变量跟踪更新
- 自动递增对象id JS构造函数(静态方法和变量)
- 使chart.js中的x轴标签按一定比例递增
- 添加带有日期或递增“版本”的注释.编号到js, CSS或HTML文件使用预处理器
- 如何将成本数据存储在Meteor JS中,使其可以递增
- 使用角度 js 递增行号