Javascript Mongoose.statics:&x27;findOne不是一个函数'+';create不是一个函数';,对不同通话类型的混淆
我有一个购物车模型,需要一个方法来检索或创建当前用户购物车 我正在将一个工作版本从controller移到model.statics,在如何从static函数中调用模型的findOne和create方法方面遇到了一些困惑 我在这两篇文章中找到了问题的答案 基本上是我最初对Javascript Mongoose.statics:&x27;findOne不是一个函数'+';create不是一个函数';,对不同通话类型的混淆,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个购物车模型,需要一个方法来检索或创建当前用户购物车 我正在将一个工作版本从controller移到model.statics,在如何从static函数中调用模型的findOne和create方法方面遇到了一些困惑 我在这两篇文章中找到了问题的答案 基本上是我最初对 CartSchema.findOne({ userId: userId }, function (err, cart) 已通过更改为来修复 this.findOne({ userId: userId }, function
CartSchema.findOne({ userId: userId }, function (err, cart)
已通过更改为来修复
this.findOne({ userId: userId }, function (err, cart)
但是相同的技术不适用于create函数,而是我最初对
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);
}
}