首页 > 解决方案 > 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

标签: node.jsarraysmongodbtypescriptmongoose

解决方案


我认为您可能需要为您的模型添加打字信息。取自博客的示例:

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


推荐阅读