node.js - 在猫鼬的判别模型中更新数组
问题描述
我有一个名为的模型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;
解决方案
所以事实证明,__t
当从根Parent
模型而不是Worker
模型更新时,您必须传入密钥 (),因为数据库不知道 aWorker
将具有哪些字段。
因此,您可以执行以下操作:
await Person.updateOne(
{ _id : person._id, __t: "Worker" },
{ $push: { locations: "UK" } }
)
在这个 Github 问题中查看更多信息
推荐阅读
- docker - Kubernetes pod 中的 Docker 容器无法通信
- javascript - 导航后如何更新参数?
- javascript - 使用 for 循环创建多个 setState 数据
- java - Java 代码执行以在 O(1) 中获得结果
- git - GitHub:如何从用户那里下载提交
- java - 双散列哈希表重新散列问题
- java - Java Selenium 没有这样的元素:无法找到元素
- facebook - 为什么我的 facebook messenger bot 帖子上的正文总是空的?
- python-3.6 - Python中的约瑟夫斯for循环
- api - HomeAway (vrbo.com) API 授权与 Oath