Mongoose .findByIdAndUpdate() 控制台记录返回,但不能分配给属性



我写这个函数来更新MongoDB中的数据:

const Sequence = require('../models/sequenceSchema');
module.exports.genNumber = function () {
let doc = Sequence.findByIdAndUpdate(
{_id: "5e1f72951c9d440000afce53"},
{$inc:{sequence_value: 1}},
{new: true},
function(err,result){
if(err) return console.log(err)

return result.sequence_value;
}
)
};

在突变解析中,我编写了以下代码:

const graphql = require('graphql');
const functions = require('../modules/functions');
const Mutation = new GraphqlObjectType({
(..)
resolve(parent,args){
let ticket = new Ticket({
name: args.name,
number: functions.genNumber(),                        
opendate: Date(),
product: args.product,
priority: args.priority,
status: args.status,
deadline: calcs.deadline(Date(),args.priority),
userid: args.userid
});

我的问题是该函数findByIdAndUpdate()更新MongoDB上的值,但没有分配给属性number:。如果我在控制台日志中返回result,它会完美显示,我不明白发生了什么。我正在使用 Graphql/Mongoose/MongoDB

发生这种情况是因为:

  1. genNumber函数不返回任何内容
  2. 如果genNumber函数返回某些内容,则它将是一个承诺,并且在创建 Ticket 时需要使用该承诺之前需要解决该承诺。

此更新的代码片段应该有效:

const Sequence = require('../models/sequenceSchema');
module.exports.genNumber = function () {
// Notice the return statement below
return new Promise((resolve, reject) => {
Sequence.findByIdAndUpdate(
{ _id: "5e1f72951c9d440000afce53" },
{ $inc: { sequence_value: 1 } },
{ new: true },
function (err, result) {
if (err) {
console.log(err);
return reject(err);
}
console.log('Result: ', result);
return resolve(result.sequence_value);
}
)
})
};

=

const Mutation = new GraphqlObjectType({
// (..)
// Notice the resolve method becomes an asynchronous
resolve: async (parent, args) => {
// Notice the await on functions.genNumber call
const number = await functions.genNumber();
let ticket = new Ticket({
name: args.name,
number: number,
opendate: Date(),
product: args.product,
priority: args.priority,
status: args.status,
deadline: calcs.deadline(Date(), args.priority),
userid: args.userid
});
}
})

相关内容

  • 没有找到相关文章