node.js - mongodb 中的日期字段在发送空值时未得到更新

标签 node.js angular mongodb mongoose

我开发了一个平均堆栈应用程序。我正在尝试更新日期字段为空值的记录。这在我的本地主机上运行良好,但在我的服务器(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));
    });
});

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

最佳答案

我做了类似的事情,在用户使用 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);
    });
});

正如你所看到的,我将它包装在一个 promise 中,这样我就可以等待发回的响应。

从你的来看,我认为你并没有告诉它使用 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);
});

关于node.js - mongodb 中的日期字段在发送空值时未得到更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54018852/

相关文章:

node.js - 适用于 Node 的 Azure SDK 对 JSON 响应中的大数字进行四舍五入

javascript - 从对象数组中获取单个属性数组

angular - 管道Angular 2动态数组长度

javascript - 如何执行 Mongoose 验证功能仅用于创建用户页面而不编辑用户页面?

node.js - 我可以用fs.readdir加载/routes/中的所有路由并用app.use(...)挂载吗?

Javascript 深复制 Squel 对象

node.js - Hapi.js - 无法在 SPA 中提供静态文件

angular - NxWorkspace 应用于具有多个 Angular 客户端的现有 .Net Core API

node.js - Redis 缓存和 Mongo 的持久性架构

node.js - 如何像sql数据库一样显示mongodb中模式之间的关系?