Node.js Mongoose集合未得到更新
我正在尝试更新mongoose集合名称Node.js Mongoose集合未得到更新,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我正在尝试更新mongoose集合名称计数器 但它没有得到更新 柜台收款 var mongoose = require('mongoose'); var Schema = mongoose.Schema; var counterSchema = new Schema({ _id: {type: String, required: true}, sequence_value: {type: Number, default: 1} }); var Counter = module
计数器
但它没有得到更新 柜台收款
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var counterSchema = new Schema({
_id: {type: String, required: true},
sequence_value: {type: Number, default: 1}
});
var Counter = module.exports = mongoose.model('Counter', counterSchema);
API
router.post('/increment',function(req, res, next){
console.log('Sequence Counter::' + getNextSequenceValue("productId"));
)};
getNextSequenceValue方法
function getNextSequenceValue(sequenceName){
var sequenceDocument = Counters.findOneAndUpdate({
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true,
upsert: true
});
console.log('Counter value::' + sequenceDocument.sequence_value);
return sequenceDocument.sequence_value;
}
但每次我点击
/increment
API时,console.log都会打印未定义的,您总是会得到未定义的,因为sequenceDocument
是一个承诺
,如果更新操作成功,它将稍后与更新的文档一起解决,如果更新操作不成功,它将以错误拒绝。在您的情况下,console.log
语句将在数据库操作完成之前运行。这是因为findOneAndUpdate
是一个异步操作,返回Promise
对象
更新可能失败,因为您以不正确的方式向findOneAndUpdate
传递参数。函数接受查询作为第一个参数,接受更新操作作为第二个参数,接受查询选项作为第三个参数
您可以按以下方式重写getNextSequenceValue
:
function getNextSequenceValue(sequenceName) {
return Counters.findOneAndUpdate(
{ // query
_id: sequenceName
},
{ $inc: { sequence_value: 1 } }, // update operation
{ // update operation options
new: true,
upsert: true
}
).then(sequenceDocument => sequenceDocument.sequence_value)
}
现在它将返回一个承诺
,该承诺将与序列值解析。您可以在控制器中使用它,如下所示:
router.post('/increment', function(req, res, next) {
getNextSequenceValue('productId')
.then(sequenceValue => {
console.log(sequenceValue)
})
.catch(error => {
// handle possible MongoDB errors here
console.log(error)
})
})
获取sequence\u值未定义
它工作正常,但我不知道我的计数器为什么会被+2更新,我也不知道。你可能会按路线走两次什么的。嗯,我只按了一次。当我打印sequenceValue
,只是为了增加,那么它就可以正常工作了。但当我在其中添加其他逻辑时,它是+2增量;getNextSequenceValue('productId')。然后(sequenceValue=>{productId=sequenceValue;//console.log(productId);})。捕获(error=>{console.log(error)})console.log(productId)代码>,但我得到了未定义的为什么?