I have some problem when I try to upsert my object with new ones(parsed from xml file),but I got the following error:
JavaScript
x
3
1
MongoError: exception: After applying the update to the document {_id: ObjectId('55be3c8f79bae4f80c6b17f8') , }, the (immutable) field '_id' was found to have been altered to _id: ObjectId('55be5f15ae
2
5597401724aab3')
3
Here is my code:
JavaScript
1
38
38
1
xmlFile.product_list.product.forEach(function (product) {
2
3
var productEntity = new Product({
4
product_id: parseInt(product.id),
5
parent_id: parseInt(product.parent_id),
6
sku: product.sku,
7
title: product.title,
8
pricenormal: parseFloat(product.price_normal),
9
pricewholesale: parseFloat(product.price_wholesale),
10
pricewholesalelarge: parseFloat(product.price_wholesale_large),
11
pricesale: parseFloat(product.price_sale),
12
weight: parseFloat(product.weight),
13
volume: parseFloat(product.volume),
14
unittype: product.unit_type,
15
status: product.status,
16
datecreating: product.datecreating,
17
sp: product.sp,
18
guaranteeext: product.guarantee_ext,
19
used: product.used,
20
statusfull: product.status_full,
21
description: null,
22
url: null
23
});
24
items.push(productEntity);
25
26
});
27
28
29
items.forEach(function (product) { //update or create new products
30
31
Product.findOneAndUpdate({product_id: product.product_id}, product, {upsert: true}, function (err) {
32
if (err) return updateDBCallback(err);
33
updateDBCallback(null, 'saved');
34
35
});
36
37
});
38
I tried to use hints like:
JavaScript
1
3
1
//product._id = mongoose.Types.ObjectId(); //doesn't work
2
//delete product._id // doesn't delete _id from product
3
but they didn’t help. So I don’t want to update my product._id , I just want to update the other fields.
Advertisement
Answer
When you do new Product()
, a new _id
is generated, along with other things. Try this:
JavaScript
1
16
16
1
items.forEach(function (product) { //update or create new products
2
3
// Es6 assign
4
var productToUpdate = {};
5
productToUpdate = Object.assign(productToUpdate, product._doc);
6
delete productToUpdate._id;
7
8
Product.findOneAndUpdate({product_id: product.product_id}, productToUpdate,
9
{upsert: true}, function (err) {
10
if (err) return updateDBCallback(err);
11
updateDBCallback(null, 'saved');
12
13
});
14
15
});
16