Mongoose update doesn't work

359 Views Asked by At

I'm trying to add blockDate into user db, but the code below doesn't make any changes. I checked out that data.username and blockDate are valid value. I get { ok: 0, n: 0, nModified: 0 } from res variable. how can I figure out what is wrong with this request?

router.post('/account/block', async (ctx, next) => {
    let data = ctx.request.body
    let fixedDate = parseInt(data.days)
    let blockDate = DateTime.local().plus({days: fixedDate}).toISO()
    let param = {
        search: { username: data.username},
        update: { $set: {blockDate: blockDate}}
    }

    try {
        console.log(param)
        let res = await User.update(param.search, param.update, {multi: true})
        console.log("res", res)
    } catch (e) {
        console.log("err", e)
    }
})
1

There are 1 best solutions below

0
On

I can't tell you if it is supposed to be a date at all without seeing your mongoose model.

If it has the type Date your mongoose validator is probably going to filter it which could be the reason that no update is happening. You could use moment for converting the string to a date. For instance (including a few other "improvements" which you may like or not):

router.post('/account/block', async (ctx, next) => {
    const data = ctx.request.body
    const fixedDate = parseInt(data.days)
    const blockDateString = DateTime.local().plus({days: fixedDate}).toISO()
    const blockDate = moment(blockDateString)
    const param = {
        search: { username: data.username},
        update: { blockDate }
    }

    try {
        console.log(param)
        const res = await User.update(param.search, param.update, {multi: true})
        console.log("res", res)
    } catch (e) {
        console.log("err", e)
    }
})