代码之家  ›  专栏  ›  技术社区  ›  weareblahs

由于BSONError,路径(pathName)处的值(数组)转换为ObjectId失败

  •  0
  • weareblahs  · 技术社区  · 1 年前

    不确定我是否做错了,但我正试图将一个具有ObjectId的数组POST到一个类型为ObjectId的模型中(参见模型),它只是返回

    "Cast to ObjectId failed for value "['66c6bd6c1bba506c04969037', '66c6bd6c1bba506c04969035', '66c6bd6c1bba506c04969034', '66c6bd6c1bba506c04969036']" (type Array) at path "tracks" because of "BSONError".
    

    也许这是JSON的问题,或者是模型本身的问题。
    这是我的模型:

    const mongoose = require("mongoose");
    const AlbumSchema = new mongoose.Schema({
      albumName: { type: String },
      mainArtist: { type: String },
      albumArt: { type: String },
      albumType: { type: String },
      tracks: { type: mongoose.Schema.Types.ObjectId, ref: "Track" },
    });
    
    module.exports = mongoose.model("Albums", AlbumSchema);
    

    这是我向该端点发出的JSON请求:

    {"tracks":["66c6bd6c1bba506c04969037","66c6bd6c1bba506c04969035","66c6bd6c1bba506c04969034","66c6bd6c1bba506c04969036"]}
    

    以下是我的Express.js代码的一部分:

    router.post("/addAlbumTrackInfo/:id", auth, async (req, res) => {
      try {
        const album = await Album.findByIdAndUpdate(req.params.id, req.body, {
          new: true,
        });
        album.save();
        res.json({status: "Successful", album})
      } catch (e) {
        res.status(400).json({ error: e.message });
      }
    });
    
    

    这个问题有什么解决办法吗?

    1 回复  |  直到 1 年前
        1
  •  0
  •   Aanchal Mehrotra    1 年前

    当AlbumSchema中的tracks字段当前被定义为接受单个ObjectId,但您试图发送一个ObjectId数组时,就会出现此问题。要存储ObjectId数组,您需要修改模式以获得数组。

    const mongoose = require("mongoose");
    
    const AlbumSchema = new mongoose.Schema({
      albumName: { type: String },
      mainArtist: { type: String },
      albumArt: { type: String },
      albumType: { type: String },
      tracks: [{ type: mongoose.Schema.Types.ObjectId, ref: "Track" }], 
    });
    
    module.exports = mongoose.model("Albums", AlbumSchema);
    
    推荐文章