我想从一个MongoDB文档返回一个特定的字段值,但是我不断地将作为返回值

我正在尝试返回一个字段值的文件在mongoose。 我有一个配方模式,在其中,我勾画了一个名为“postedBy”的值,基本上是提交食谱的人的_id。 以下是配方模型的代码:

let recipeSchema = new Schema({ // I have other values in the schema, but for clarity sake, // I clearly have the field value defined in the schema model. postedBy: { type: String, required: true, index: true } }); 

现在这里是我有问题的代码:

  /// Here I make my function that returns the postedBy field value in ///question let getRecipeMaker = (recipeId) => { return Recipe .findOne({_id: recipeId}) .then((recipe) => { /// So far this is good, this console.log is printing out /// the field value I want console.log('What is being returned is ' + recipe.postedBy); return recipe.postedBy; }) .catch((err) => { console.log(err) }); }; // Then here, I am setting the returned result of the function to a // variable. My req.params.recipeId is already outlined // in the router this code is in, so that's not the issue. let value_ = getRecipeMaker(req.params.recipeId) .then((chef) => { // This console.log is printing the value that I want to the // console. So I should get it. console.log('chef is ' + chef); }); /// But whenever I am console.logging the variable, I keep getting ///[object Promise] instead of the value I want console.log('value_ is ' + value_); 

谁能帮我吗。

这是你用诺言工作的一个问题。 您的最终控制台日志不在承诺链之内。 您的最终console.log实际上是在数据库有机会查询结果之前执行的。 如果你想要的范围超出承诺,你可以返回厨师后,你得到你的配方制造商

 let value_ = getRecipeMaker(req.params.recipeId) .then((chef) => { // This console.log is printing the value that I want to the // console. So I should get it. console.log('chef is ' + chef); return chef; }); 

那么你的最终控制台日志是在哪里

 value_.then(chef => { console.log(chef); });