Tuesday 23 May 2017

Cast to ObjectId failed for value "ObjectId" with mongoose

I have need to use mongoose find method with "_id" instead of findById.

In my router I receive a correct string "_id" from my front end app:

req.query.where="591f47d10d957323386f0c42".

But when I run the app I get an error:

My error is:

"ObjectId" message:"Cast to ObjectId failed for value "ObjectId {↵  path: '591f47d10d957323386f0c42',↵  instance: 'ObjectID',↵  validators: [],↵  setters: [],↵  getters: [],↵  options: undefined,↵  _index: null }" at path "_id" for model "Ag_escalaatendimento""
name:
"CastError" path:"_id" stringValue: ""ObjectId {path: '591f47d10d957323386f0c42',  instance: 'ObjectID',  validators: [],  setters: [],  getters: [],  options: undefined,↵  _index: null }""

//code

'use strict';
const express = require('express');
const router = express.Router();
const Ag_escalaatendimento = require('../models/ag_escalaatendimento');

const callback=function(err,data,res){
         //if (err) console.log(err);
         if (err) return res.status(500).json(err);
         return res.status(200).send(data);
    }   



//get all

router.get('/',function(req,res,next){  
        var mongoose = require('mongoose');
        var ObjectId = mongoose.Schema.Types.ObjectId;

        //Here I have req.query.where: "591f47d10d957323386f0c42".
        var qrySearch={"_id": new ObjectId(req.query.where)};
            Ag_escalaatendimento.find(qrySearch)
            .exec( (err,data) => {
               callback(err,data,res)
            })
        });



via Luiz Alves

No comments:

Post a Comment