javascript Mongoose更新嵌套子文档

cyvaqqii  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(153)

我尝试使用request.body更新mongoose的子文档,但没有传递子文档_id。更新工作正常,但mongoose从子文档中删除了_id
假设使用以下模式

// schemas.js
const mongoose = require('mongoose');

const motorSchema = new mongoose.Schema({
    type: String,
    volume: Number,
});

const carSchema = new mongoose.Schema({
    manufacturer: String,
    model: String,
    motors: [motorSchema],
});

const userSchema = new mongoose.Schema({
   username: String,
   email: String,
   cars: [carSchema]
});
const mongoose = require('mongoose');
// import schemas
const userSchema = require('userSchema');
const carSchema = require('carSchema');
const motorSchema = require('motorSchema');
// create models
const User = mongoose.model("User", userSchema);
const Car = mongoose.model("Car", carSchema);
const Motor = mongoose.model("Motor", motorSchema);

module.exports.updateCar = async function (request, response) {
    const condition = {
        _id: new mongoose.Types.ObjectId(request.body.userId),
        "cars._id": new mongoose.Types.ObjectIt(request.body.carId)
        };

    // Build object for partial update
    const set = {};
    for(let field in reqest.body){
        set[`cars.$.${field}`] = request.body[field];
    }

    const update = {
        $set = set;
    }

    User.findOneAndUpdate(condition, update, {new: true, overwrite: false},
        (error, user) => {
            if(error) {response.send(error)}
            response.json(user);
        }
}

问题是我所有的_id属性都将在motors数组中被覆盖。我怎样才能强制mongoose作为默认值而不更改_id属性呢?

hvvq6cgz

hvvq6cgz1#

如果我没有理解错的话,等效的mongoDB语法将使用arrayFilters,所以您也可以修改查询以使用它:
例如:

User.findOneAndUpdate(
  condition,
  {$set: {"cars.$[item].size": "large"}},
  {arrayFilters: [{"item._id": new mongoose.Types.ObjectIt(request.body.carId)}]}
)

了解它在playground example上的工作原理
根据此方法,您的代码需要查询的选项部分中的arrayFilters$set部分中的$[<identifier>]

const set = {};
    for(let field in reqest.body){
        set[`cars.$[item].${field}`] = request.body[field];
    }

    const update = {
        $set = set;
    }

    User.findOneAndUpdate(
        condition, 
        update, 
        {
            arrayFilters: [{"item._id": new mongoose.Types.ObjectIt(request.body.carId)}],
            new: true, overwrite: false
        },
        (error, user) => {
            if(error) {response.send(error)}
            response.json(user);
        }

相关问题