【问题标题】:MongoDB Typescript Error "Type 'ObjectId' is not assignable to type 'never'MongoDB Typescript 错误“类型‘ObjectId’不可分配给类型‘从不’
【发布时间】:2021-07-06 14:56:32
【问题描述】:

作为我的 GraphQL 解析器之一,我有这个函数,它可以将艺术家 ID 添加到用户的 Liked Artists 对象 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.js arrays mongodb typescript mongoose


    【解决方案1】:

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

    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

    【讨论】:

    • 遗憾的是,这段代码并没有完全解决问题,因为它添加了更多问题,例如 findOneAndUpdate 有一个错误说它没有调用签名。原来的问题也没有消失。我现在通过将类型设置为“从不”作为临时修复来解决此问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 2022-06-29
    • 1970-01-01
    • 2020-11-09
    • 2019-03-21
    • 2018-09-19
    • 2020-07-29
    • 1970-01-01
    相关资源
    最近更新 更多