我有一个购物车模型,需要一种方法来检索或创建当前用户购物车。
我正在将一个工作版本从控制器移动到model.statics,并且在如何从静态内部调用模型的 findOne 和创建方法时遇到了一些困惑功能
我在这两个帖子mongooge-model-findone-typeerror-object-has-no-method-findone和mongoose-typeerror-on-a-models-findone-method
中找到了我的问题的答案基本上是我对
的原始号召CartSchema.findOne({ userId: userId }, function (err, cart)
通过更改为
来修复this.findOne({ userId: userId }, function (err, cart)
但是相同的技术不适用于创建功能,而是我原来的
调用CartSchema.create(cart, function (err, newCart)
使用不同的风格修复
mongoose.model('Cart').create(cart, function (err, newCart)
以下是工作代码以及对已有内容和抛出异常的注释
CartSchema.statics.getMyCart = function (userId, callback) {
try {
// CartSchema.findOne({ userId: userId }, function (err, cart)
// will throw
// TypeError: CartSchema.findOne is not a function
//
// this.findOne({ userId: userId }, function (err, cart)
// OK
this.findOne({ userId: userId }, function (err, cart) {
if (err) {
return callback(err, null, false);
}
if (cart) {
// If cart exists for this user, then execute callback for additional actions against this cart
return callback(null, cart, false);
}
cart = {
userId: userId,
items: []
};
// CartSchema.create(cart, function (err, newCart) {
// will throw
// TypeError: CartSchema.create is not a function
//
// this.create(cart, function (err, newCart) {
// will throw
// TypeError: this.create is not a function
mongoose.model('Cart').create(cart, function (err, newCart) {
if (err) {
return callback(err, null, false);
}
// Cart has been created for this user, now execute callback for additional actions against this cart
return callback(null, newCart, true);
});
});
} catch (e) {
l.exception(e);
}
}