mongoose 如何为Typicode帖子和用户定义MongoDB模式?

gxwragnw  于 2022-12-13  发布在  Go
关注(0)|答案(1)|浏览(110)

您好,我想从https://jsonplaceholder.typicode.com/postshttps://jsonplaceholder.typicode.com/users植入数据
我为User定义了mongodb模式,比如

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  username: {
    type: String,
  },
  email: {
    type: String,
  },
  address: {
    street: {
      type: String,
    },
    suite: {
      type: String,
    },
    city: {
      type: String,
    },
    zipcode: {
      type: String,
    },
    geo: {
      lat: {
        type: String,
      },
      lng: {
        type: String,
      },
    },
  },
  phone: {
    type: String,
  },
  website: {
    type: String,
  },
  company: {
    name: {
      type: String,
    },
    catchPhrase: {
      type: String,
    },
    bs: {
      type: String,
    },
  },
});

module.exports = mongoose.model("User", UserSchema);

和用于Post

const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({
  title: {
    type: String,
  },
  body: {
    type: String,
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
});

module.exports = mongoose.model("Post", PostSchema);

我正在使用seeder函数(如

const importData = async () => {

try {
    await Post.deleteMany();
    await User.deleteMany();

    const createdUsers = await User.insertMany(users);
    console.log("created users", createdUsers);

    const samplePosts = await Post.insertMany(posts);
    console.log("sampleProducts", samplePosts);
    process.exit();
  } catch (error) {
    console.error(`${error}`.red.inverse);
    process.exit(1);
  }
};

但是,我得到的错误为
验证错误:userId:由于“BSONTypeError”,在路径“userId”中为值“1”(类型编号)强制转换为ObjectId失败
这个错误意味着什么?我该如何解决这个错误?

eeq64g8w

eeq64g8w1#

我认为这太晚了,但我希望这个答案对任何得到相同错误的主体都有用。此错误〉〉在路径“userId”处,值“1”(类型编号)转换为ObjectId失败,原因是“BSONTypeError”
指出我们在脚本中使用了错误的数据类型,解决方法是将数据类型从数字更改为字符串

相关问题