简体   繁体   中英

Mongoose update doesn't work

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)
    }
})

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)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM