node.js为什么剂量mongodb抛出转换错误

时间:2019-03-14 00:07:32

标签: node.js mongodb mongoose

//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);

将事件添加到数据库并获得单个事件的效果很好,但是当我从数据库中获取所有事件时,都抛出错误并且无法对现有事件进行任何更新

1 个答案:

答案 0 :(得分:1)

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

尝试一下:

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

希望它能对您有所帮助。