如何更新 [Schema.Types.Mixed]?
How do I update a [Schema.Types.Mixed]?
我正在使用 Schema.Types.Mixed 存储“配置文件”,这是我的架构
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
profiles:{
type: Schema.Types.Mixed
}
}
假设我有一个包含以下值的文档:
{
name: "XYZ"
profiles:{
"fb" : {
"name": "XYZ",
"pic": "source",
"link": "www.fb.com/xyz"
},
"twitter" : {
"name": "XYZ",
"pic": "source",
"link": "www.twitter.com/xyz"
}
}
}
我想添加另一个字段“youtube”。我如何编写 updateOne 查询,以便在配置文件中插入这个新字段?以及如何更新这些内部字段的值?假设我只想更新 fb 的“link”字段,我该怎么做?
您可以使用 Mongo
的聚合管道
How do I write updateOne query such that it upserts this new field in
profiles?
db.profiles.aggregate( [
{
$addFields: {
"profiles.youtube": "add the data here"
}
}
] )
And how do I update values of these inner fields?
db.profiles.aggregate( [
{
$addFields: {
"profiles.twitter.name": "add the data here"
}
}
] )
这将更新现有字段。如果您想对整个集合进行更改,此管道效果很好。有关详细信息,请查看 this.
如果你想为一份文件这样做,你可以这样做:
db.profiles.update({"name": "XYZ" },{$set : {"profiles.youtube":"add data here"}});
// to update existing data
db.profiles.update({"name": "XYZ" },{$set : {"profiles.twitter":"add data here"}});
我正在使用 Schema.Types.Mixed 存储“配置文件”,这是我的架构
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
profiles:{
type: Schema.Types.Mixed
}
}
假设我有一个包含以下值的文档:
{
name: "XYZ"
profiles:{
"fb" : {
"name": "XYZ",
"pic": "source",
"link": "www.fb.com/xyz"
},
"twitter" : {
"name": "XYZ",
"pic": "source",
"link": "www.twitter.com/xyz"
}
}
}
我想添加另一个字段“youtube”。我如何编写 updateOne 查询,以便在配置文件中插入这个新字段?以及如何更新这些内部字段的值?假设我只想更新 fb 的“link”字段,我该怎么做?
您可以使用 Mongo
的聚合管道How do I write updateOne query such that it upserts this new field in profiles?
db.profiles.aggregate( [
{
$addFields: {
"profiles.youtube": "add the data here"
}
}
] )
And how do I update values of these inner fields?
db.profiles.aggregate( [
{
$addFields: {
"profiles.twitter.name": "add the data here"
}
}
] )
这将更新现有字段。如果您想对整个集合进行更改,此管道效果很好。有关详细信息,请查看 this.
如果你想为一份文件这样做,你可以这样做:
db.profiles.update({"name": "XYZ" },{$set : {"profiles.youtube":"add data here"}});
// to update existing data
db.profiles.update({"name": "XYZ" },{$set : {"profiles.twitter":"add data here"}});