Mongoose - 无法更新深度嵌套对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongoose - 无法更新深度嵌套对象相关的知识,希望对你有一定的参考价值。

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]
});

所以你看到它:Category - > products [] - > items []我想更新数据库中的items数组中的Objects并设置(此时未定义的字段为“selldate”。

我的代码片段如下所示:

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();
                                                        });
                                                    });
答案

我发布了一个包含文档和子文档的示例程序。请检查此信息,如果您需要其他信息,请与我们联系 架构

const PostSchema = new Schema({
        title  : String
    });

    const HomeSchema = new Schema({
        "name" : {
            type : String,
            required : true
        },
        "city" : {
            type : String,
            required : true
        },
        post : [PostSchema]
    });

保存文档和子文档

    const cat = new HomeModel({
        name: "tiger",
        city : "africa",
        post : [{
            "title" : "tiger post"
        }]
    });
    cat.save((user) => {
        console.log("saved");
        console.log(user);
    })
    .catch((err)=>{
        console.log("err");
        console.log(err);
    });

要更新文档

 HomeModel.update({name : "tiger"},{city : "china123"})
        .then((home)=>{
            console.log("updated");
            console.log(home);
        })
        .catch((error) => {
            console.log("error");
            console.log(error);
        });

添加新的子文档

HomeModel.findOne({name : "tiger"})
        .then((home) => {
            console.log("findone")
            console.log(home);
            home.post.push({"title" : "monkey"});
            home.save();
        })
        .catch((err)=>{
            console.log("error");
        });

要更新现有的子文档

method:1
HomeModel.findOne({name : "tiger"})
        .then((home) => {
            console.log("findone")
            const tes=home.post.id("5a3fe65546c99208b8cc75b1");
            tes.set({"title" : "it workssdfg"});
            home.save();
        })
        .catch((err)=>{
            console.log("error");
        });

使用子文档ID查找父文档

 HomeModel.findOne({"post._id" : "5a3fe65546c99208b8cc75b1"})
            .then((home) => {
                console.log("findone")
                console.log(home);
            })
            .catch((err)=>{
                console.log("error");
            });

以上是关于Mongoose - 无法更新深度嵌套对象的主要内容,如果未能解决你的问题,请参考以下文章

如何从深度嵌套的文档中 $pull (mongoose)

如何在 mongodb/mongoose 的嵌套数组中检查是不是存在并更新对象?

Mongoose:通过 findOneAndUpdate 查询使用嵌套对象数组的总和更新父子数据属性不起作用

React:使用 Hooks 为深度嵌套对象设置状态

更新 mongoose json 对象似乎不起作用

Mongoose更新嵌套数组