I need help with a Query on a Backend- RestAPI of mongoDB using mongoose

2

This is the model of the object to which I ask the question

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,

email: { type: String, required: true},
nombre: { type: String, required: true},
password: { type: String, required: true},
phone:  { type: String, required: true},
publicaciones : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Inmueble'}]

 });
 module.exports = mongoose.model('User', userSchema);

and I want to insert a property in the arrangement of publications objects of the type Property, with the following post request that does not work.

router.post('/:userID/publicaciones', (req, res, next) => {
const id = req.params.userID;
const idinmueble = req.body;
User.update({ _id: id }, { $push: { "publicaciones": idinmueble} })
    .exec()
    .then(result => {
        res.status(200).json({
            message: 'User inserted inmuebles',
            request: {
                type: 'POST',
                url: 'http://localhost:3000/users/' + id
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });

 });

doing the Post request com postman throws me the following error:

{
    "error": {
        "message": "Cast to [ObjectId] failed for value \"[{\"idinmueble\":\"5b137a4ed0471d38c4b5925b\"}]\" at path \"publicaciones\"",
        "name": "CastError",
        "stringValue": "\"[{\"idinmueble\":\"5b137a4ed0471d38c4b5925b\"}]\"",
        "kind": "[ObjectId]",
        "value": "[{\"idinmueble\":\"5b137a4ed0471d38c4b5925b\"}]",
        "path": "publicaciones",
        "reason": {
            "message": "Cast to ObjectId failed for value \"{ idinmueble: '5b137a4ed0471d38c4b5925b' }\" at path \"publicaciones\"",
            "name": "CastError",
            "stringValue": "\"{ idinmueble: '5b137a4ed0471d38c4b5925b' }\"",
            "kind": "ObjectId",
            "value": {
                "idinmueble": "5b137a4ed0471d38c4b5925b"
            },
            "path": "publicaciones"
        }
    }
}
    
asked by Samuel Carmona 24.06.2018 в 02:00
source

1 answer

0

is having trouble converting the string idinmueble to ObjectId (which is the id), try:

const ObjectId = require('mongodb').ObjectID;
User.update({ _id: id }, { $push: { "publicaciones": ObjectId(idinmueble)} })

Surely mongoose has some equivalent function

    
answered by 24.06.2018 / 02:10
source