MongoJS 添加到现有数组
MongoJS add to existing array
我正在尝试添加到 mongoDB 中的现有数组。这是我所拥有的,但它当然是不正确的,因为在它尝试添加它之后所有数据都被清除了:
db.cardKeeper.update(
{_id: ObjectId('5621c5ac30895e5776e4d1ea')},
{
$push:{'cardKeeperApp.appData.cardDecks':deckObject}
}
)
deckObject
我要添加到数组中的对象看起来像这样
var deckObject = {
name: productName,
searchName: productItem,
price:{
purchasePrice: productCost,
averageWorth: priceAverageFixed,
lowWorth: lowestSoldAmount,
highWorth: highestSoldAmount
}
}
如您所见,cardKeeperApp.appData.cardDecks
是我的数组,它包含更多看起来像 deckObject
的信息
如果这对完整对象有帮助,我正在尝试添加到 cardDecks
数组。我已将字段标记为 null
{
"_id" : ObjectId("5635ddf82f4c220f4f932af2"),
"cardKeeperApp" : {
"appData" : {
"cardDecks" : [
{
"name" : "Some Name",
"searchName" : "Some+Name",
"price" : {
"purchasePrice" : null,
"averageWorth" : null,
"lowWorth" : null,
"highWorth" : null
}
}
],
"allDeckTotalWorth" : null
}
}
}
我找到了解决方案。 findAndModify
by query:{_id:ObjectId}
然后更新和推送:
db.cardKeeper.findAndModify({query:{_id: ObjectId('5635ddf82f4c220f4f932af2')},
update: {$push:{'cardKeeperApp.appData.cardDecks': deckObject}},
new:true}, function (err, doc) {
res.json(doc);
});
我正在尝试添加到 mongoDB 中的现有数组。这是我所拥有的,但它当然是不正确的,因为在它尝试添加它之后所有数据都被清除了:
db.cardKeeper.update(
{_id: ObjectId('5621c5ac30895e5776e4d1ea')},
{
$push:{'cardKeeperApp.appData.cardDecks':deckObject}
}
)
deckObject
我要添加到数组中的对象看起来像这样
var deckObject = {
name: productName,
searchName: productItem,
price:{
purchasePrice: productCost,
averageWorth: priceAverageFixed,
lowWorth: lowestSoldAmount,
highWorth: highestSoldAmount
}
}
如您所见,cardKeeperApp.appData.cardDecks
是我的数组,它包含更多看起来像 deckObject
如果这对完整对象有帮助,我正在尝试添加到 cardDecks
数组。我已将字段标记为 null
{
"_id" : ObjectId("5635ddf82f4c220f4f932af2"),
"cardKeeperApp" : {
"appData" : {
"cardDecks" : [
{
"name" : "Some Name",
"searchName" : "Some+Name",
"price" : {
"purchasePrice" : null,
"averageWorth" : null,
"lowWorth" : null,
"highWorth" : null
}
}
],
"allDeckTotalWorth" : null
}
}
}
我找到了解决方案。 findAndModify
by query:{_id:ObjectId}
然后更新和推送:
db.cardKeeper.findAndModify({query:{_id: ObjectId('5635ddf82f4c220f4f932af2')},
update: {$push:{'cardKeeperApp.appData.cardDecks': deckObject}},
new:true}, function (err, doc) {
res.json(doc);
});