【问题标题】:Date field in mongodb not get update when sending a null value发送空值时,mongodb中的日期字段未得到更新
【发布时间】:2019-05-29 20:09:13
【问题描述】:

我开发了一个平均堆栈应用程序。我正在尝试使用 Date 字段的空值更新记录。这在我的本地主机上运行良好,但在我的服务器(Aws Ec2)上运行良好。它包含更新前的先前值。

我也尝试过“未定义”但仍然是同样的问题。

访问mongodb set null in update

router.put('/editAssign/:id',(req,res)=>{
    if(!ObjectId.isValid(req.params.id))
        return res.status(400).send('No record with given id : $(req.params.id)');

    var assignment = {
        name: req.body.name,
        code: req.body.code,
        appointmentTime: req.body.appointmentTime,
        scheduledTime:req.body.scheduledTime,
        countEndTime: null
    };

    Assignment.findOneAndUpdate(req.params.id,{$set:assignment},{new:true},(err,doc)=>{
        if(!err)
            res.send(doc);
        else
            console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));
    });
});

我希望它也能在我的服务器上运行。

【问题讨论】:

    标签: node.js angular mongodb mongoose


    【解决方案1】:

    当用户使用 Mongoose 登录时,我在更新用户的最后登录日期时做了类似的事情。

    const authUser: any = await new Promise((res, rej) => {
        User.findOneAndUpdate({ _id: user[0]._id }, { last_login: date }, {new: true}, (err: any, user:any) => {
            if (err) rej(err);
            res(user);
        });
    });
    

    如你所见,我将它包装在一个承诺中,这样我就可以等待发回的响应。

    从您的角度来看,您似乎并没有告诉它使用findByIdAndUpdate 而不是findOneAndUpdate,因为您只传递了ID。所以更新后的应该是这样的。

    Assignment.findByIdAndUpdate(req.params.id, assignment, {new:true}, (err,doc)=>{
        if(err) console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));
    
        return res.send(doc);
    });
    

    所以在上面的那个中,我们传递了findByIdAnyUpdate 的ID,我们只是传递了分配。如果它包含与架构相同的所有字段,它将仅使用最新字段进行更新。

    编辑:

    您可以尝试的另一种方法是:

    Assignment.findByIdAndUpdate(req.params.id, assignment, {new: true}, (err: any, result: any) => {
        if(err) console.log('Error in Assignment Update: '+JSON.stringify(err,undefined,2));
    
        // Reasign with new assignment and save
        result = assignment;
        result.save();
    
        return res.send(result);
    });
    

    【讨论】:

    • 那为什么它在我的本地主机上运行良好?我也应用了您的解决方案,但同样的问题在我的服务器上仍然存在,但在 localhost 上没有。
    • 让我看看我的服务器上是否也发生了这种情况
    • 你的解决方案也是正确的。我的服务器正在做一些奇怪的问题。它正在更新约会时间,但不是计数结束时间。两者的日期类型相同。
    • 看看我用猫鼬更新的另一种方法
    • 在您的机器和服务器上检查您的 mongo 版本
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多