我想在我的一个集合上设置一个自动递增ID(_id太长)。为此,我创建了一个' counter'收集按照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);
};
希望以上是有道理的。非常感谢任何帮助。
答案 0 :(得分:0)
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);
});
};
答案 1 :(得分:0)
以为我会用保罗的答案把我最终的结果放在一边。
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")
}
});
};