Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Mongoose集合未得到更新_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 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

我正在尝试更新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.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),但我得到了
未定义的
为什么?