我想在我的一個集合(_id太長)上設置自動遞增ID。要做到這一點我創建了一個「櫃檯」收集的建議在許多職位,包括Mongos官方網站(下圖):在node.js中使用計數器集合來增加ID字段
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);
};
希望上面說得通。任何幫助非常感謝。
謝謝保羅,那就是訣竅。我需要去閱讀一些事情的異步方面。 – ricky89