Mongoose - Modle.update()更新错误文档 - Cast Error

时间:2017-04-24 09:51:23

标签: node.js express mongoose

我需要一些帮助来澄清一些事情。

我有一个模型:

##
# The following Script is checking the current HPPowerProfile Setting on the local Server
# and set it to Maximum_Performance if its not already set.
#
# Also it set´s the UEFIBootOrder to HDD firts (Target:0, Lun:0)
##


# Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File C:\mysecurestring.txt
# Set Access Credentials

    $username = "*******"
    $password = cat C:\mysecurestring.txt | Convertto-SecureString
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

# Set ILO Hostname

    $sv = hostname 
    $ri = $sv.replace("YY","XX")

# Connect to HPBios

    $conObj = Connect-HPBIOS $ri -Credential $cred -DisableCertificateAuthentication

# Check current BootMode (depending on Boot Mode, other cmdlet´s will be executed)

    $bm = $conObj | Get-HPBIOSBootMode | select -Expand BootMode
        if ( $bm -eq "UEFI Mode")
            {echo "UEFI"}
        else 
            {echo "echo $bm"}

# Check current Server Power Profile

    $pr = Get-HPBIOSPowerProfile $conObj | select -Expand HPPowerProfile   
        if (-not( $pr -eq "Maximum Performance"))
            {$conObj | Set-HPBIOSPowerProfile -HPPowerProfile Maximum_Performance}
        else 
            {echo "No change needed"}

# Find HDD and move it to Boot Order #1

    $bo = Get-HPBIOSUEFIBootOrder $conObj | select -Expand UEFIBootOrder | Where DeviceName -like "*Drive(Target:0, Lun:0)" | select -Expand Index
        if (-not( $bo -eq "1"))
            {$conObj | Set-HPBIOSUEFIBootOrder -UEFIBootOrder "$bo,1"}
        else 
            {echo "No change needed"}

新文档的创建非常完美。当谈到更新某些文件时,我遇到了一些麻烦。

当我这样做时(下面的代码): =它只更新第一个文档,即使id不匹配

var Event = new Schema({
   event_code: String
 , segments: [Segment]
});

当我这样做时(下面的代码): =它给我一个错误(见下文)

function edit_event (id, new_name, callback) {
  Event.update(id, {$set:{event_code: new_name}}, function(err, doc) {
    if (err) throw err;
    callback();
  });
}

使用findByIdAndUpdate时出错: function edit_event (id, new_name, callback) { Event.findByIdAndUpdate(id, {$set:{event_code: new_name}}, function(err, doc) { if (err) throw err; callback(); }); }

拜托,我绝望了! :/

更新

我发现我正在尝试传递的ID会以“”存储在其周围,因此当我查找具有匹配ID的文档时,它会在其周围添加一对“”,因此最终会像“ “ID”,“

更新2

当我列出我的所有文件时,它会返回:

Cast to ObjectId failed for value ""58fdbde31bff83141b376508"" at path "_id" for model "Event"

然后,当我将id存储在HTML表单中时,它会在其周围添加额外的“”...这与event_code不同。这是为什么 ?

1 个答案:

答案 0 :(得分:1)

您似乎执行了不必要的JSON.stringify,这就是您在id周围获得引号的原因。致电JSON.parse应解决问题:

Event.findByIdAndUpdate(JSON.parse(id), {$set:{event_code: new_name}}, ...