Subqueries in mongoose

1

I have a problem when making subqueries in mongoose, I have two collections one place and another material , the place collection has an array of materials ids added by a user .

Now what I'm trying to do is to be able to update a place only if the attribute of the material collection assigned = false , otherwise it will not be updated, after adding the material to the place this material must be updated assigned = true so that it can no longer be added to another place.

Then I leave my schemes:

// Material
const materialSchema = new Schema({

    title: { type: String, required: [true, 'El titulo es necesario'] },
    url: { type: String, required: [true, 'La url es necesaria'] },
    asignado: { type: Boolean, required: true, default: false },
    rating: { type: Number, default: 0, min: 0, max: 5 },
    usuario: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true,
    },
}, {
    timestamps: true
});

// Lugar
const lugarSchema = new Schema({

    nombre: { type: String, required: [true, 'El nombre es necesario'] },
    materiales: [{
        type: Schema.Types.ObjectId,
        ref: 'Material',
        required: false,
    }],
    usuario: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true,
    },
}, {
    timestamps: true
});

Something like that I want to do:

    let id = req.params.id;
        var body = req.body;
        const user = req.currentUser._id;

        let lug = {
            nombre: body.nombre,
            materiales: body.materiales,
            usuario: req.currentUser._id
        };

        const mat = body.materiales;

        // buscar los materiales que se van a agregar al lugar solo si asignado = false
        await materialModel.find({ _id: mat }, { asignado: 'false' }, (err, guardado) => {
                // actualiza solo si asignado = false 
                // y guardamos la referencia del material en el lugar
                await lugarModel.findByIdAndUpdate(id, lug, { new: true });
        });

        // actualizamos el material para que no se pueda agregar después
        // query aquí

Way in which I put the data for now

Relationship between collections

    
asked by yvan Garcia 16.08.2018 в 21:02
source

0 answers