我无法修改猫鼬模型

时间:2019-06-30 01:22:01

标签: node.js mongodb mongoose

我正在使用Mongoose Model,这是我的代码

import { Router, Request, Response } from 'express'
import UserModel from '../../../models/user.model'
import { error500 } from '../../../global/errors'
import AreaModel from '../../../models/area.model'


const UserChangesRoute = Router()


UserChangesRoute.get( '/:id', ( req: Request, res: Response ) => {

    const id: String = req.params.id
    const pop_user  = { path: 'modification.user', select: 'name last_name' }
    UserModel.find( { _id: id }, 'modification' ).sort({ 'modification.date': 1 })
    .populate( pop_user )
    .lean()
    .exec( ( err: any, data: any ) => {
        if( err ) {
            return res.status( 500 ).json( { message: error500, err } )
        }
        // I used to: data = data.toObject()
        for( let i = 0; i < data[0].modification.length; i++ ) {

            if( data[0].modification[ i ][ 'updated' ][ 0 ] === 'area' ) {
                AreaModel.findById( data[0].modification[ i ][ 'updated' ][ 1 ], 'name', ( e: any, area: any ) => {
                    if( !e ) data[0].modification[ i ][ 'updated' ][ 1 ] = area.name
                });

                AreaModel.findById( data[0].modification[ i ][ 'updated' ][ 2 ], 'name', ( e: any, area: any ) => {
                    if( !e ) data[0].modification[ i ][ 'updated' ][ 2 ] = area.name
                });
            }
        }
        res.status( 200 ).json( { data } )
    })
})


export default UserChangesRoute

我无法用新数据替换当前数据,恰好在for循环上,我使用了.lean()并且无法正常工作,data.toObject()都没有引发错误,toObject是没有定义

我在

上尝试了所有可能的解决方案

Cant modify objects from Mongoose document search

Node.Js Express and Mongoose Response Model Modify

How do you turn a Mongoose document into a plain object?

仍然无法正常工作

我做错了什么?

这是数据响应的一个节点

{
  date: "2019-06-30T00:43:53.714Z"
  updated: ["area", "5d144312e62fba41783ff36f", "5d0e785d6713bb28ac11c9e3", "Área"]
}

0 个答案:

没有答案