【问题标题】:Cast Error: Cast to String failed for value when try to find it转换错误:尝试找到值时转换为字符串失败
【发布时间】:2017-08-24 11:03:18
【问题描述】:

我在这里遇到了一个很奇怪的问题,我可以通过猫鼬保存数据但不能进行查询。 代码如下:

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: 未处理的承诺 拒绝(拒绝 id:1):ValidationError:CastError:Cast to 值“{_id:58dd019b1a06731b0990b878,存储: 'Store-Name-Here',类别:[],__v: 0 }" 在路径“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);
})

【问题讨论】:

  • 你是怎么查询的?请添加功能
  • Category.findOne({store: 'Store-Name-Here'}).then(store => {/*something here*/}, err => {/*err here*/} );
  • 一次尝试,Category.findOne({store: "Store"}).then(store => {/*something here*/}, err => {/*err here*/});,看看会发生什么
  • 它返回 null
  • 错误消失了?当你给的时候?

标签: node.js express mongoose mongoose-schema


【解决方案1】:

我想我找到了问题所在。我尝试向名为CategoryScheme.static.init() 的类别方案添加一个静态方法。删除该方法后,一切正常。我想也许出于某种原因已经有一个名为init() 的方法,而我创建了一个可能已经覆盖它的方法。这就是导致错误的原因。

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 2016-01-02
    • 1970-01-01
    • 2013-12-30
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    相关资源
    最近更新 更多