更新文档,但出现错误:对于未定义的值,强制转换为字符串失败

Update document with error: Cast to string failed for value undefined

本文关键字:失败 字符串 未定义 转换 文档 错误 更新      更新时间:2023-09-26

我有一个简单的文档,上面有名称(require),描述(可选)。在我的模型中,我使用有效 id 更新文档,并传递未定义值的说明,因为我想从文档中删除此属性。但是,我收到以下错误:message=在路径"description"处为值"未定义"转换为字符串失败,名称=强制转换错误,类型=字符串,值=未定义,路径=描述。当用户不提供描述时,如何在更新时删除描述属性?可能吗?

谢谢

/*jslint indent: 2, node: true, nomen: true*/
'use strict';
var Schema = require('mongoose').Schema;
var mongoose = require('mongoose');
var mongooser = require('../../lib/mongooser');
// Schema
var schema = new Schema({
  name: {
    required: true,
    set: mongooser.trimSetter,
    trim: true,
    type: String,
    unique: true
  },
  description: {
    set: mongooser.trimSetter,
    trim: true,
    type: String
  }
});
// Export
module.exports = mongoose.model('Role', schema);

角色.js

var update = function (model, callback) {
    var test = { name: 'Users', description: undefined };
    RoleSchema.findByIdAndUpdate(model.id, test, function (error, role) {
      callback(error, role);
    });
};

如果有人不想下拉到本机驱动程序,请参阅此答案 https://stackoverflow.com/a/54320056/5947136

这里的问题是在架构中使用类型作为键。

var schema = new Schema({
 name: {
    required: true,
    set: mongooser.trimSetter,
    trim: true,
    type: String, // <-- This is causing the issue
    unique: true
  },
  description: {
    set: mongooser.trimSetter,
    trim: true,
    type: String // <-- This is causing the issue
  }
});

请参阅上述答案以获取解决方案,而无需本机驱动程序。

尝试像这样下降到本机驱动程序:

var update = function (model, callback) {
   RoleSchema.update({_id: model.id}, {$unset: {description: 1 }}, callback);
   });
};