【问题标题】:Cannot read property 'save' of undefined无法读取未定义的属性“保存”
【发布时间】:2019-03-25 07:10:29
【问题描述】:

我将 GraphQL 与 NodeJs 和 Mongoose 一起使用(我猜 GraphQL 在这里无关紧要)

当我运行查询时,我收到一条消息,说无法读取未定义的属性 save

      resolve (parent, args) {
        let books
        book.find(
            {
            name: args.name
            }, function (error, result){
                console.log(result.length)
                if (result.length == 0) { 

                    console.log(args.name)
                    books = new book({
                        name: args.name, 
                        genre: args.genre,
                        authorName: args.authorName
                    })    
                    Author.find(
                        {
                        name: args.authorName
                        },
                        function (err, results) {
                            if (results.length == 0) {
                                let author = new Author({ 
                                    name: args.authorName
                                })
                            author.save()
                        }
                        });
                }
            })
                return books.save()
        }

这是我的代码,上面注意两个console.log。第一个 console.log 显示长度为零,第二个 console.log 确实有一个值

另外,作者和书是我正在导入的猫鼬模式

const Author = require("../models/author.js")
const book = require("../models/book.js")

为了范围,我在resolve (parent, args) { 下方声明了let books

问题:现在,我对 JS 没有太多经验,所以有人可以帮助我并在这里分享我做错了什么吗?

【问题讨论】:

  • 更新了我的问题
  • .find 方法是异步的,在查询执行之前调用.save
  • @FrankerZ 回调在他调用.save后执行
  • 您能告诉我们您在控制台中的日志顺序吗?因为我认为您将收到未定义的错误,然后结果值被记录...将 books.save 保留在与作者案例相同的异步调用中...

标签: javascript node.js mongoose


【解决方案1】:

你的问题是 book.find 函数是异步的。这意味着包含return books.save() 的行将在 book.find 函数的回调之前执行。设置 books 变量后,您可以在回调中移动对 book save 的调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2021-03-15
    • 2016-07-03
    • 2021-05-10
    相关资源
    最近更新 更多