Mee*_*ack 19 javascript mongodb node.js
当我尝试用新的对象(从xml文件解析)中插入我的对象时,我遇到了一些问题,但是我收到以下错误:
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
5597401724aab3')
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
xmlFile.product_list.product.forEach(function (product) {
var productEntity = new Product({
product_id: parseInt(product.id),
parent_id: parseInt(product.parent_id),
sku: product.sku,
title: product.title,
pricenormal: parseFloat(product.price_normal),
pricewholesale: parseFloat(product.price_wholesale),
pricewholesalelarge: parseFloat(product.price_wholesale_large),
pricesale: parseFloat(product.price_sale),
weight: parseFloat(product.weight),
volume: parseFloat(product.volume),
unittype: product.unit_type,
status: product.status,
datecreating: product.datecreating,
sp: product.sp,
guaranteeext: product.guarantee_ext,
used: product.used,
statusfull: product.status_full,
description: null,
url: null
});
items.push(productEntity);
});
items.forEach(function (product) { //update or create new products
Product.findOneAndUpdate({product_id: product.product_id}, product, {upsert: true}, function (err) {
if (err) return updateDBCallback(err);
updateDBCallback(null, 'saved');
});
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用如下提示:
//product._id = mongoose.Types.ObjectId(); //doesn't work
//delete product._id // doesn't delete _id from product
Run Code Online (Sandbox Code Playgroud)
但他们没有帮助.所以我不想更新我的product._id,我只是想更新其他字段.
Alf*_*rez 26
当你这样做时new Product(),_id会产生一个新的东西以及其他东西.试试这个:
items.forEach(function (product) { //update or create new products
// Es6 assign
var productToUpdate = {};
productToUpdate = Object.assign(productToUpdate, product._doc);
delete productToUpdate._id;
Product.findOneAndUpdate({product_id: product.product_id}, productToUpdate,
{upsert: true}, function (err) {
if (err) return updateDBCallback(err);
updateDBCallback(null, 'saved');
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25126 次 |
| 最近记录: |