本文介绍了对于值“ObjectId",强制转换为 ObjectId 失败与猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用带有_id"而不是 findById 的 mongoose find 方法.

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

在我的路由器中,我从前端应用程序收到了正确的字符串_id":

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

req.query.where="591f47d10d957323386f0c42".

使用 robomongo,下一个运行良好:

With robomongo, the next works well:

db.getCollection('ag_escalaatendimentos').find({'_id':ObjectId('59247524723dec26aca239ed')})

但是当我运行应用程序时出现错误:

But when I run the app I get an error:

我的错误是:

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

//代码

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

推荐答案

正如 Neil 在评论中提到的,Mongoose 会在适当的时候自动将字符串转换为 ObjectIds.但是,问题的根本原因是您使用了错误的 ObjectId 类.Mongoose 实际上提供了两个不同的同名类:

As Neil mentioned in the comments, Mongoose will automatically convert strings to ObjectIds when appropriate. However, the root cause of your problem is that you're using the wrong ObjectId class. Mongoose actually provides two different classes with the same name:

  • mongoose.Schema.Types.ObjectId
  • mongoose.Types.ObjectId

您应该在定义模式时使用第一个,在为查询显式创建 ObjectId 时使用第二个.替换您定义 ObjectId 的那一行可修复您的代码:

You should use the first one when defining schemas and the second one when explicitly creating ObjectIds for queries. Replacing the one line where you define ObjectId fixes your code:

var mongoose = require('mongoose');
var ObjectId = mongoose.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)
    })
});

这篇关于对于值“ObjectId",强制转换为 ObjectId 失败与猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:07