【问题标题】:Call statics in mongoose.Schema from another mongoose.Schema从另一个 mongoose.Schema 调用 mongoose.Schema 中的静态
【发布时间】:2023-03-24 21:10:01
【问题描述】:

我用的是 mongoose Schema,我有两个 js 文件;

first.js:

 const mongoose = require('mongoose')

    var FirstSchema= new mongoose.Schema({

        F1: {
            type: Boolean,
            default: null
        },
        F2: {
            type: Boolean,
            default: null
        }
    })


    FirstSchema.statics.add_to = function (_param) {
           //DO SOMETHING
    }

    var First = mongoose.model('First', FirstSchema )

    module.exports = {
        First
    }

socound.js:

 const mongoose = require('mongoose')
 var { First } = require('../func/first.js')

 var SocoundSchema = new mongoose.Schema({

    S1: {
        type: Boolean,
        default: null
    },
    S2: {
        type: Boolean,
        default: null
    }
})


 SocoundSchema.statics.add_other = function (_param) {

        return new Promise((resolve, reject) => {

            return First.add_to(_param).then((Result) => {
                return resolve(Result);
            }, (err) => {
                return reject(err);
            })

         })
}

var socound = mongoose.model('socound', SocoundSchema )

module.exports = {
    socound 
}

当我调用 First.add_to 时,它不起作用。

我测试了不同的代码和方法,但都失败了……

如何在另一个 mongooseSchema 中使用 mongooseSchema 中的静态?有解决办法吗?

【问题讨论】:

    标签: javascript node.js mongoose ecmascript-6 promise


    【解决方案1】:

    在 socound.js 中,您的 .add_other 函数有问题(缺少括号):

    SocoundSchema.statics.add_other = function (_param) {
    
        return new Promise((resolve, reject) => {
    
            return First.add_to(_param)
            .then((Result) => {
                return resolve(Result);
            }, (err) => {
                return reject(err);
            })
    
         })
    }
    

    你在调用 First.addd_to() 时使用 .then,所以它应该是一个 Promise,我只是在代码中添加了异步

    First.js:

    FirstSchema.statics.add_to = async function (_param) {
           //DO SOMETHING
           console.log('ayy');
           return true;
    }
    

    【讨论】:

    • 我修复了 SocoundSchema 并将异步添加到 FirstSchema,但问题没有解决。
    • @M.ZF,它会抛出错误吗?如果可以,你能提供吗?
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 2019-03-24
    • 2019-09-03
    • 2020-05-29
    • 2023-03-12
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    相关资源
    最近更新 更多