node.js - MongoDB Typescript 错误“类型‘ObjectId’不可分配给类型‘从不’
问题描述
作为我的 GraphQL 解析器之一,我有这个函数,它可以将 Artist ID 添加到用户的 Liked Artists Object ID 数组中。代码如下:
async likeArtist(_parent, args, _context, _info) {
await User.findOneAndUpdate(
{ _id: args.userID },
{ $push: { likedArtists: new ObjectId(args.artistID as string) } },
{
new: true,
runValidators: true,
}
);
return true;
},
当我在实际网站上试用时,它似乎工作正常。奇怪的是 $push 所在的行抛出了一个错误,特别是在“likedArtists”中说:
... gave the following error.
Type 'ObjectId' is not assignable to type 'never'
这是用户的架构
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema({
image: String,
email: String,
posts: Array,
likedPosts: Array,
likedArtists: Array,
balance: String,
notifications: Array,
tutorial: {
type: Boolean,
default: true,
},
name: String,
age: String,
country: String,
birthday: String,
phone: String,
newUser: Boolean,
notifRead: Boolean,
artLevel: String,
artStyles: Array,
artKinds: Array,
userBio: String,
// More to come
});
export default mongoose.models.User || mongoose.model("User", UserSchema);
如何删除打字稿错误?当我尝试这样做时,它会妨碍我npm run build
。
解决方案
我认为您可能需要为您的模型添加打字信息。取自博客的示例:
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
firstName: string;
lastName: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true }
});
// Export the model and return your IUser interface
export default mongoose.model<IUser>('User', UserSchema);
参考:https ://tomanagle.medium.com/strongly-typed-models-with-mongoose-and-typescript-7bc2f7197722
推荐阅读
- ruby-on-rails - Rails 中嵌套属性错误的自定义哈希
- apache-spark - 使用 Apache Spark 加入两个大表
- python - 在python中处理不同长度数组列表的最有效方法
- php - 用于 laravel 问题的 unisharp 文件管理器
- r - 在 mlr 中使用 MICE 进行插补
- asp.net-core - API 构建不使用自定义 URL 构建
- javascript - 来自地址栏的 Safari 请求(在后台预加载热门)
- c# - 使用 Autofac 和 EF Core 3.1 的内存泄漏(从 2.2 迁移后)
- javascript - 如何在循环中设置状态?
- php - 在 PDO 类中调用变量