首页 > 解决方案 > node.js为什么剂量mongodb抛出铸造错误

问题描述

//this error appear
{
    "error": {
        "message": "Cast to ObjectId failed for value \"events\" at path \"_id\" for model \"user\"",
        "name": "CastError",
        "stringValue": "\"events\"",
        "kind": "ObjectId",
        "value": "events",
        "path": "_id"
    }
}

//when execute this code
exports.get_all_events = (req, res, next) => {
    Event.find({})
    .populate("creator","name _id",user) // must define model reference
        .then(result => {
            console.log(result);
            res.status(200).json({ result });
        }).catch(err => {
            console.log(err);
            res.status(500).json({ error: err });
        });
}

事件架构

const mongoose = require('mongoose');
// creat event schema
const eventSchema =  mongoose.Schema({
    name: {
        type: String,
        required: [true, 'name is required']
    },
    location: {
        type: String,
        required: [true, 'location is required']
    },
    date: {
        type: String,
        required: [true, 'data is required']
    },
    description: {
        type: String,
        required: [true, 'description is required']
    },
    creator: {
        _id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "users"
        }
    }
});
module.exports = mongoose.model("events", eventSchema);

用户模式

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({

    email: {
        type: String,
        required: true,
        unique: true,
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    password: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true

    },
    post: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "posts"
        }
    ],

    event: [
        {
            type: mongoose.Schema.Types.ObjectId,
            // it point to collection
            ref: "events"
        }
    ]
});
module.exports = mongoose.model('users', userSchema);

它很好地将事件添加到数据库并获取单个事件它可以工作但是当我从数据库中获取所有事件时抛出转换错误并且无法对存在事件进行任何更新

标签: node.jsmongodbmongoose

解决方案


我认为您填充事件文档有点错误。

尝试这个:

Event.find({})
    .populate("creator._id","name _id")
    .then(result => {
         console.log(result);
         res.status(200).json({ result });
     }).catch(err => {
         console.log(err);
         res.status(500).json({ error: err });
     });

我认为您不需要函数中的任何第三个参数.populate(),您已经在您的schema中定义了它应该从以下位置填充:

//look here, you have already defined it in your schema
creator: {
    _id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "users" //this says which collection it should be populated from
    }
}

我希望它可以帮助你。


推荐阅读