【问题标题】:trouble using promises with mongoose对猫鼬使用 Promise 时遇到问题
【发布时间】:2016-09-18 09:28:06
【问题描述】:

谁能告诉我为什么这个承诺设置不起作用。它应该删除文档然后添加它然后找到它然后控制台它。它不是在安慰数据。

  var Comp = require("./models/company.js");
  var arr = [
    {name : "comp1",industry : "industry1", ranking: 20},
    {name : "comp2",industry : "industry2", ranking: 5},
    {name : "comp3",industry : "industry3", ranking: 10}
  ]

  var output = {};  
  var promise =  Comp.find({}).exec()
  promise.then(function(res){
        console.log("removed")
        return Comp.remove({}).exec()
    })
    .then(function(){
        return Comp.create(arr).exec()
    })

    .then(function(data){
         return Comp.find({}).exec();
    })
    .then(function(data){
        console.log(data)
    })

编辑::

发现错误

[TypeError: Comp.create(...).exec is not a function]

【问题讨论】:

    标签: javascript node.js mongodb mongoose promise


    【解决方案1】:

    Model.create 返回一个承诺,因此无需在返回值上调用.exec()

    .then(function(){
        return Comp.create(arr);
    })
    

    【讨论】:

    • 太酷了。因此查询不会返回承诺,但如果您使用 exec 它会返回。但是 createsave 返回一个承诺,所以你不应该使用 exec 。对吗?
    • @jackblank 没错。如有疑问,请查看 API docs 以获得 Mongoose。
    猜你喜欢
    • 2020-02-23
    • 2017-01-29
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 2019-02-09
    • 2021-04-10
    • 2023-03-18
    相关资源
    最近更新 更多