首页 > 解决方案 > 在猫鼬的判别模型中更新数组

问题描述

我有一个名为的模型Person,它有一个鉴别器,"Worker"它给它一个额外locations的数组字段。

我正在尝试将一个元素推送到位置数组而不通过 fetch/modify/save 方法(因此我可以updateMany稍后使用它来同时更新多个文档)。

为什么下面的代码中没有发生这种情况?我也试过findByIdAndUpdate这个findOneAndUpdate

index.js

const { connect } = require("mongoose");

const Person = require("./Person");

connect("mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb", {
  useNewUrlParser: true,
}, async () => {
  console.log("Database connected")
  const person = await Person.create(
    {
      __t: "Worker",
      name: "John", 
      locations: ["America"],
    },
  )

  console.log(person);
  // Outputs: 
  // {
  //   locations: [ 'America' ],
  //   _id: 5eba279663ecdbc25d4d73d4,
  //   __t: 'Worker',
  //   name: 'John',
  //   __v: 0
  // }

  await Person.updateOne(
    { _id: person._id }
    {
      $push: { locations: "UK" }, 
    },
  )

  const updated = await Person.findById(person._id);

  console.log(updated);
  // (Updating "locations" was unsuccessful)
  // Outputs: 
  // {
  //   locations: [ 'America' ],
  //   __t: 'Worker',
  //   _id: 5eba279663ecdbc25d4d73d4,
  //   name: 'John',
  //   __v: 0
  // }
});

Person.js

const { Schema, model } = require("mongoose");

const personSchema = Schema({
  name: String,
});

const Person = model("Person", personSchema);

Person.discriminator(
  "Worker",
  Schema({
    locations: [String],
  })
);

module.exports = Person;

标签: node.jsmongodbmongoose

解决方案


所以事实证明,__t当从根Parent模型而不是Worker模型更新时,您必须传入密钥 (),因为数据库不知道 aWorker将具有哪些字段。

因此,您可以执行以下操作:

await Person.updateOne(
  { _id : person._id, __t: "Worker" },
  { $push: { locations: "UK" } }
)

在这个 Github 问题中查看更多信息


推荐阅读