【问题标题】:Mongoose - Cannot Update update deeply nested ObjectsMongoose - 无法更新更新深度嵌套的对象
【发布时间】: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


【解决方案1】:

我发布了一个包含文档和子文档的示例程序。 请检查此内容,如果您需要更多信息,请告诉我

架构

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多