更新文档,但出现错误:对于未定义的值,强制转换为字符串失败
Update document with error: Cast to string failed for value undefined
我有一个简单的文档,上面有名称(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);
});
};
相关文章:
- 如何避免JSON.stringify在特殊情况下返回undefined,从而为JSON.parse创建字符串失败
- 当字符串包含 HTML 标记时,JSON 解析失败
- 在页面加载时获取查询字符串值失败
- 字符串测试失败
- 使用 match 匹配某些字符串,正则表达式失败
- 为什么这个字符串比较在Jest的期望中没有失败
- 为什么当我使用变量而不是整数或字符串时初始化日期对象失败
- 字符串比较 JavaScript 中的失败
- 在 Javascript 中将带有空格的字符串数组转换为小写,然后在 Webkit 中搜索它们失败
- 在 JavaScript 中将字符串转换为 int 失败
- 错误=字符串.$variable - 失败
- 尝试追加 html 字符串失败与 jQuery
- 字符串解析、JSON Stringify 和 GSON 日期解析失败
- 更新文档,但出现错误:对于未定义的值,强制转换为字符串失败
- PHP Regex失败,'&'字符串;在javascript中(正确地)传递
- jquery/javascript文件验证2字符串编译(文件扩展)失败
- 字符串replace()失败
- 查询字符串URL的Javascript URL验证失败
- Javascript 正则表达式匹配一些字符串,但在其他看似相同的字符串上失败
- 查询字符串功能失败