node.js - 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);
它很好地将事件添加到数据库并获取单个事件它可以工作但是当我从数据库中获取所有事件时抛出转换错误并且无法对存在事件进行任何更新
解决方案
我认为您填充事件文档有点错误。
尝试这个:
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
}
}
我希望它可以帮助你。
推荐阅读
- oracle - PL/SQL 显示带有条件的表中的数据
- python - bash PBS 作业中的 Python 版本
- c++ - Range-v3 是否提供一元绑定功能?如果没有,我如何为管道操作员提供自定义功能的支持?
- java - 如何导入受信任的 SSL 证书
- linux - 如何在 bash 的 GUI 对话框中打印命令行菜单
- python - 如何将一行零添加到矩阵中?
- flutter - 如何从有状态小部件类 Flutter 访问小部件状态
- json - 为什么会出现“错误:无效 JSON:意外令牌”?(对此全新!)
- docker-compose - 测试容器:无法初始化 DockerComposeContainer
- imagemagick - ImageMagick 在 Singularity 容器内转换 OOMing