我正在尝试将一个新对象添加到一个子文档中,我知道它的'ean'。我目前有下面的代码,这取代了子文档,而不是添加到它,任何想法我怎么能实现这个?
由于
var info = {
"merchant_id": 12354,
"price_current": "test",
"price_rrp": "test",
"aff_link": "test",
"merchant_product_id": 12345,
}
addUpdateMerchantToProduct: function(info) {
var now = new Date();
var query = { "ean" : 5055534336205};
var update = { "merchants" : [{
"merchant_id": info.merchant_id,
"price_current": info.display_price,
"price_rrp": info.rrp_price,
"aff_link": info.aw_deep_link,
"merchant_product_id": info.merchant_product_id,
"aw_image_url": "",
"cost_scoop": "",
"created_at": now,
"updated_at": now
}]};
Products.findOneAndUpdate(query, update, function (err, product) {
if (err) console.error(err);
});
}
答案 0 :(得分:0)
你想使用$ push。您的更新正在转换为$ set运算符,该运算符将使用包含单个对象的数组替换商家字段。
addUpdateMerchantToProduct: function(info) {
var now = new Date();
var query = { "ean" : 5055534336205};
var update = {
$push: {
"merchants" : {
"merchant_id": info.merchant_id,
"price_current": info.display_price,
"price_rrp": info.rrp_price,
"aff_link": info.aw_deep_link,
"merchant_product_id": info.merchant_product_id,
"aw_image_url": "",
"cost_scoop": "",
"created_at": now,
"updated_at": now
}
}
};
Products.findOneAndUpdate(query, update, function (err, product) {
if (err) console.error(err);
});