【发布时间】:2018-06-04 16:21:12
【问题描述】:
var ItemSchema = new Schema({
item: {type: String, required: false},
ts: {type: String, required: true},
selldate: {type: Number, required: false},
replaced: [ReplaceSchema]
});
var ProductSchema = new Schema({
title: {type: String, required: true, trim: true}, //name of the products
artNo: {type: Number, required: true},
catId: {type: String, required: true},
productType: {type: String, required: true}, //physical, textbased or downloadable product | can be 'dl', 'txt', 'phy'
tid: {type: String, required: false}, //only needed for physical products for providing a tid
minItems: {type: Number, required: true},
ts: {type: Number, required: true}, // when was the product online
buyCount: {type: Number, required: true}, // baught how many times
description: {type: String}, //more about the product
price: {type: Number, required: true}, // how much?
discounts: [DiscountSchema], // discount objects
items: [ItemSchema],
images: [], // fullsize images of the product
thumbnails: [], // small preview images of the product
// isPublic: {type: Boolean, required: true}, // if product should be published or not
itemCount: {type: Number, required: false} // how many items exists on the product
});
var CategorySchema = new Schema({
name: {type: String, required: true},
ts: {type: Number, required: true},
products: [ProductSchema]
});
所以你会看到它:类别 -> products[] -> items[] 我想更新数据库中的项目数组中的对象并设置(此时未定义字段“selldate”。
我的代码 sn-p 如下所示:
Category.getProductOfCategory(productId, function(err, boughtProduct) {
if (err) {
res.send({
status: false,
data: err
})
} else {
// console.log('BoughtProduct: ', boughtProduct.products[0])
var bought = boughtProduct.products[0];
// console.log('theItem: ', bought.items.id(item._id));
bought.items.id(item._id).selldate = Date.now();
bought.save(function(err, results) {
if (err) {
res.send({
status: false,
data: err
})
} else {
// i is increased because we need it on line 5
// console.log('itemerr', err)
console.log('saved', results);
j++;
// the next() function is called when you
// want to move to the next item in the array
next();
}
});
}
});
但是数据库中没有发生任何事情。我没有得到任何错误,但“结果”只是未定义。 你能帮帮我吗?
更新:
我有一个解决方案,但它只能在执行一次时才起作用.. 之后,它再也没有发生... 代码:
Category.findById(catId, function (err, data) {
if (err) console.log(err);
data.products.id(productId).items.id(item._id).selldate = Date.now();
data.save(function (err, result) {
if (err) console.log(err);
j++;
next();
});
});
【问题讨论】:
-
没人能帮我吗?
-
使用 findById 或 findByAnyField 方法验证 items 数组是否有对应的对象,如果返回对象则使用对象本身更新更改。
-
Category.getProductOfCategor 已经在执行此操作,但无法正常工作
-
我无法让它工作 :( 令人沮丧.. 有什么方法可以做这个更新查询吗?
-
我会在某个时候发布解决方案
标签: arrays node.js mongoose nested