【问题标题】:Mongoose create a new object within a static functionMongoose 在静态函数中创建一个新对象
【发布时间】:2016-01-10 14:50:43
【问题描述】:

如何在架构中定义的静态方法之一中创建新对象?

我基本上有

UserSchema.statics.createUser = function (username, password, cb) { .. }

我希望能够在函数内保存用户对象的新实例。我想在该方法中执行var user = new User(...) 之类的操作,但它当然不起作用,因为尚未创建用户模型。

我该怎么办?

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    当您第一次调用静态函数时,this 绑定到模式的模型。你可以这样做:

    someSchema.static('foo', function() {
        const newUser = new this({
            username: username, 
            password: password,
        });
        newUser.save(cb);
    })
    

    不要用等效的粗箭头替换匿名函数(我知道你想这样做!)。 this 没有正确的范围。

    【讨论】:

    • 我之前尝试过,但没有成功。但我刚刚意识到我是在回调中做到的。谢谢!
    • 我试过了,但它是“这不是构造函数”。
    • 对于其他搜索此问题的人。 @NisanthSojan 当我遇到此错误时,是因为我将函数定义为 () => {},但您应该使用 function() {}。
    • 试过了,但是说this is not a constructor
    • @Mendes 我通过不使用箭头函数来修复它,因此可以访问this。这里提到了mongoosejs.com/docs/guide.html#statics
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2021-08-13
    • 2017-04-20
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多