基于来自另一个模型的异步查询在模型中设置虚拟字段

时间:2021-07-12 19:35:24

I want to have a user setting (in a user model) that is derived from the sum of values in another model.

我想要一个用户设置(在用户模型中),该用户设置是从另一个模型中的值的总和派生的。

What I have tried to do is create a virtual value using a query like this:

我试图做的是使用如下查询创建一个虚拟值:

var schemaOptions = {
    toObject: {
        virtuals: true
    }
    ,toJSON: {
        virtuals: true
    }
};
/**
 * User Schema
 */

var UserSchema = new Schema({
  firstname: String,
  lastname: String,
  email: String,
  username: String,
  provider: String,
  phonenumber: Number,
  country: String,
  emailverificationcode: {type:String, default:'verifyme'},
  phoneverificationcode: {type:Number, default:4321 },
  emailverified: {type:Boolean, default:false},
  phoneverified: {type:Boolean,default:false},
}, schemaOptions)

UserSchema
    .virtual('credits')
    .get(function(){
        //Load Credits model
        var Credit = mongoose.model('Credit');
        Credit.aggregate([
            { $group: {
                _id: '5274d0e5a84be03f42000002',
                currentCredits: { $sum: '$amount'}
            }}
        ], function (err, results) {
                if (err) {
                    return 'N/A'
                } else {
                    return results[0].currentCredits.toString();
                    //return '40';
                }
            }
        );
    })

Now, this gets the value but it fails to work correctly (I cannot retrieve the virtual 'value' credits). I think this is because of the async nature of the call.

现在,这获得了价值,但它无法正常工作(我无法检索虚拟'价值'信用额度)。我认为这是因为呼叫的异步性质。

Can someone suggest the correct way to achieve this?

有人可以建议正确的方法来实现这一目标吗?

Once again many thanks for any input you can provide.

再次感谢您提供的任何输入。

Edit:

So I am trying to follow the suggested way but no luck so far. I cannot get my 'getCredits' method to call.

所以我试图按照建议的方式,但到目前为止没有运气。我无法调用我的'getCredits'方法。

Here is what I have so far:

这是我到目前为止:

UserSchema.method.getCredits = function(cb) {
        //Load Credits model
        var Credit = mongoose.model('Credit');
        Credit.aggregate([
            { $group: {
                _id: '5274d0e5a84be03f42000002',
                currentCredits: { $sum: '$amount'}
            }}
        ], function (err, results) {
                cb(results);
            }
        );
};


var User = mongoose.model('User');

User.findOne({ _id : req.user._id })
.exec(function (err, tempuser) {
    tempuser.getCredits(function(result){

    });
})

Any ideas? Thanks again

有任何想法吗?再次感谢

1 个解决方案

#1


1  

There are a few issues with your implementation:

您的实施存在一些问题:

UserSchema.method.getCredits
           ^^^^^^ should be 'methods'

Also, you have to make sure that you add methods (and virtuals/statics) to your schema before you create the model, otherwise they won't be attached to the model.

此外,您必须确保在创建模型之前向模式添加方法(和虚拟/静态),否则它们将不会附加到模型。

So this isn't going to work:

所以这不会起作用:

var MySchema = new mongoose.Schema(...);
var MyModel  = mongoose.model('MyModel', MySchema);

MySchema.methods.myMethod = ... // too late, model already exists

Instead, use this:

相反,使用这个:

var MySchema = new mongoose.Schema(...);

MySchema.methods.myMethod = ... 

var MyModel  = mongoose.model('MyModel', MySchema);

I would also advise you to always check/propagate errors.

我还建议你经常检查/传播错误。

#1


1  

There are a few issues with your implementation:

您的实施存在一些问题:

UserSchema.method.getCredits
           ^^^^^^ should be 'methods'

Also, you have to make sure that you add methods (and virtuals/statics) to your schema before you create the model, otherwise they won't be attached to the model.

此外,您必须确保在创建模型之前向模式添加方法(和虚拟/静态),否则它们将不会附加到模型。

So this isn't going to work:

所以这不会起作用:

var MySchema = new mongoose.Schema(...);
var MyModel  = mongoose.model('MyModel', MySchema);

MySchema.methods.myMethod = ... // too late, model already exists

Instead, use this:

相反,使用这个:

var MySchema = new mongoose.Schema(...);

MySchema.methods.myMethod = ... 

var MyModel  = mongoose.model('MyModel', MySchema);

I would also advise you to always check/propagate errors.

我还建议你经常检查/传播错误。