gpt4 book ai didi

node.js - Mongo 子文档数组中的多子文档更新

转载 作者:可可西里 更新时间:2023-11-01 09:59:19 24 4
gpt4 key购买 nike

我正在尝试更新 Mongo 集合中的多个子文档,其中同一集合中可能有多个匹配项。不幸的是,它只会更新每个文档中具有匹配项的第一个子文档。

代码如下:

var mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1/touchbits');

var PartsSchema = new mongoose.Schema({
type: String
, partNbr: Number
});

var ProductSchema = new mongoose.Schema({
sku: { type: String, unique: true }
, parts: [PartsSchema]
});

Product = mongoose.model('Product', ProductSchema);

var cigars = new Product({
sku: 'cigar123',
parts: [{type: 'tobacco', partNbr: 4},
{type: 'rolling paper', partNbr: 8},
{type: 'tobacco', partNbr: 4}]
});
var cigarillo = new Product({
sku: 'cigarillo456',
parts: [{type: 'tobacco', partNbr: 4},
{type: 'crush paper', partNbr: 12}]
});

cigars.save(function(err, product1) {
if(err) { console.log("err1: " + err); return err; }
console.log("saved: " + product1);
cigarillo.save(function(err, product2) {
if(err){ console.log("err2: " + err); return err; }
console.log("saved: " + product2);
Product.update({ "parts.type": 'tobacco' },
{ $set: { "parts.$.partNbr": 5 } },
{ multi: true },
function(err, numAffected) {
if (err) { console.log("err3: " + err); return err; }
console.log("records updated: " + numAffected);
Product.find({}, function(err, docs) {
if (err) { console.log("err4: " + err); return err; }
console.log("updated data: " + docs);
Product.remove(function(err) {
if (err) { console.log("err5: " + err); return err; }
process.exit();
});
});
});
});
});

然后当我运行它时,我得到以下结果:

saved: { __v: 0,
sku: 'cigar123',
_id: 51c9229b7fe80ef71e000002,
parts:
[ { type: 'tobacco', partNbr: 4, _id: 51c9229b7fe80ef71e000005 },
{ type: 'rolling paper',
partNbr: 8,
_id: 51c9229b7fe80ef71e000004 },
{ type: 'tobacco', partNbr: 4, _id: 51c9229b7fe80ef71e000003 } ] }
saved: { __v: 0,
sku: 'cigarillo456',
_id: 51c9229b7fe80ef71e000006,
parts:
[ { type: 'tobacco', partNbr: 4, _id: 51c9229b7fe80ef71e000008 },
{ type: 'crush paper',
partNbr: 12,
_id: 51c9229b7fe80ef71e000007 } ] }
records updated: 2
updated data: { sku: 'cigar123',
_id: 51c9229b7fe80ef71e000002,
__v: 0,
parts:
[ { type: 'tobacco', partNbr: 5, _id: 51c9229b7fe80ef71e000005 },
{ type: 'rolling paper',
partNbr: 8,
_id: 51c9229b7fe80ef71e000004 },
{ type: 'tobacco', partNbr: 4, _id: 51c9229b7fe80ef71e000003 } ] },{ sku: 'cigarillo456',
_id: 51c9229b7fe80ef71e000006,
__v: 0,
parts:
[ { type: 'tobacco', partNbr: 5, _id: 51c9229b7fe80ef71e000008 },
{ type: 'crush paper',
partNbr: 12,
_id: 51c9229b7fe80ef71e000007 } ] }

请注意,“cigars”文档中的第二个“tobacco”记录的 PartNbr 仍然是 4 而不是 5。有谁知道如何更改更新以更新数组中与查询条件匹配的所有子文档?

最佳答案

在一个请求中更新多个子文档的功能尚未实现。

它在 https://jira.mongodb.org/browse/SERVER-1243 有一个当前请求

关于node.js - Mongo 子文档数组中的多子文档更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17289565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com