Cast Error: Cast to String failed for value when try to find it
Cast Error: Cast to String failed for value when try to find it
我遇到了一个很奇怪的问题,我可以通过猫鼬保存数据但不能进行查询。
这是代码:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
store : {type: String, required: true, unique: true},
categories : [{
parent : String,
name : String,
}],
});
CategorySchema.index({store: 1, update_at: -1});
module.exports = mongoose.model('Category', CategorySchema);
当我尝试执行查询时,出现此错误:
(node:7412) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): ValidationError: CastError: Cast to
String failed for value "{ _id: 58dd019b1a06731b0990b878, store:
'Store-Name-Here', categories: [], __v: 0 }" at path "store"
我对其他集合有非常相似的架构,它们工作正常但不是这个。
我是这样查询的:
Category.findOne({store: 'Store-Name-Here'}).exec().then(result => console.log(result), err => console.log(err));
和
Category.find().exec(function(err, result) {
if (err)
return next(err);
console.log(result);
})
我想我找到了问题所在。我试图将一个静态方法添加到名为 CategoryScheme.static.init()
的类别方案中。删除该方法后,一切正常。我想也许出于某种原因已经有一个名为 init()
的方法,我创建了一个可能覆盖了它的方法。这就是导致错误的原因。
我遇到了一个很奇怪的问题,我可以通过猫鼬保存数据但不能进行查询。 这是代码:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
store : {type: String, required: true, unique: true},
categories : [{
parent : String,
name : String,
}],
});
CategorySchema.index({store: 1, update_at: -1});
module.exports = mongoose.model('Category', CategorySchema);
当我尝试执行查询时,出现此错误:
(node:7412) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: CastError: Cast to String failed for value "{ _id: 58dd019b1a06731b0990b878, store: 'Store-Name-Here', categories: [], __v: 0 }" at path "store"
我对其他集合有非常相似的架构,它们工作正常但不是这个。
我是这样查询的:
Category.findOne({store: 'Store-Name-Here'}).exec().then(result => console.log(result), err => console.log(err));
和
Category.find().exec(function(err, result) {
if (err)
return next(err);
console.log(result);
})
我想我找到了问题所在。我试图将一个静态方法添加到名为 CategoryScheme.static.init()
的类别方案中。删除该方法后,一切正常。我想也许出于某种原因已经有一个名为 init()
的方法,我创建了一个可能覆盖了它的方法。这就是导致错误的原因。