Mongoose findOneAndUpdate not working if I dont specify the field to update

Related searches

I currently have the following mongoose function in a hapi.js api call

    server.route({
    method: "PUT",
    path:"/api/blockinfo/{hash}",
    handler: async (request, h) => {
        try{
            var jsonPayload = JSON.parse(request.payload)
            console.log(jsonPayload)
            var result = await BlockModel.findOneAndUpdate(request.params.hash, {$set: { height : jsonPayload[Object.keys(jsonPayload)[0]]}},  {new: true});
            return h.response(result);
        }catch{

            return h.response(error).code(500);
        }
    }
})

Its goal is basically to update a value using a PUT. In the case above, it will update the field height, and it will work just fine.

But what if I want to update an arbitrary field?

For example my object format is the following:

{"_id":"5cca9f15b1b535292eb4e468", "hash":"d6e0fdb404cb9779a34894b4809f492f1390216ef9d2dc0f2ec91f95cbfa89c9", "height":301651, "size":883, "time":1556782336, "__v":0}

In the case above I updated the height value using the $set, but what if I decide to input 2 random fields to update, for example, size and time.

This would be my put in postman:

{
    "size": 300,
    "time": 2
}

Well obviously it wont work in the code above because those fields are missing in the set.

SO how do i make that set to recognize automatically whatever it needs to update?

I tried to simplify it with the following code but it wont update anything

    server.route({
    method: "PUT",
    path:"/api/blockinfo/{hash}",
    handler: async (request, h) => {
        try{
            var result = await BlockModel.findOneAndUpdate(request.params.hash, request.payload,  {new: true});
            return h.response(result);
        }catch{

            return h.response(error).code(500);
        }
    }
})

Schema

const BlockModel = Mongoose.model("blocks", {
  hash: String,
  height: Number,
  size: Number,
  time: Number
});

Problem is with your hash key. First parameter/argument in findOneAndUpdate function should be the key value pair. And here you are directly putting the key.

So it should be

handler: async (request, h) => {
  try {
    const { hash } = request.params
    var result = await BlockModel.findOneAndUpdate({ hash }, request.payload,  { new: true })
    return h.response(result)
  } catch (err) {
    return h.response(error).code(500)
  }
}

Update:

You are defining mongoose model in incorrect way. Schema is not just an object. It should be mongoose object. Something like this

const schema = new Mongoose.Schema({
  hash: String,
  height: Number,
  size: Number,
  time: Number
})

export default Mongoose.model("blocks", schema)

Mongoose findOneAndUpdate and runValidators not working � Issue , My user schema has an email field that has required set to true but each time Mongoose findOneAndUpdate and runValidators not working #3124 but if I don't mention it in the setOnInsert is does not complain, if its value is in the update (and the query, if upsert is specified), because mongoose really� Because Mongoose by default creates a new MongoDB ObjectId ( this hidden _id field) every time you pass it a Javascript Object to update the field of a document. To go around you can tell Mongoose to not create a new ObjectId, by making sure your mongoose schema is as followed: Folder - Models - Stock.js "_id": false - Has to be added to the Schema

handler: async (request, h) => {
        try{
            var result = await BlockModel.findOneAndUpdate(request.params.hash, JSON.parse(request.payload ),  {new: true});
            return h.response(result);
        }catch{

            return h.response(error).code(500);
        }
    }

SInce we are updating a JSON, the payload must be in JSON format

Mongoose v5.10.0: API docs, If not set, the MongoDB driver defaults to using 30000 (30 seconds). Set to false to make findOneAndUpdate() and findOneAndRemove() use native if you want your database operations to fail immediately when the driver is not connected Note 2: You don't have to call this if your schema contains index or unique field. Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.

You have not added $set in your simplified code, adding that it should work. Send payload as an object with the required fields.

server.route({
    method: "PUT",
    path:"/api/blockinfo/{hash}",
    handler: async (request, h) => {
        try{
            var result = await BlockModel.findOneAndUpdate(request.params.hash, { $set: request.payload } ,  {new: true});
            return h.response(result);
        }catch{

            return h.response(error).code(500);
        }
    }
})

Mongoose v5.10.0: Validation, Validation; Built-in Validators; The unique Option is Not a Validator; Custom You can manually mark a field as invalid (causing validation to fail) by using once for // a given collection, so you normally don't need to do this // in production . Update validators are off by default - you need to specify the runValidators option. mongoose 4.4.4 node v5.4.0 mongo db version v3.2.1 When using findOneAndUpdate with $set, to set value of a field whose value is a map {}, it returns an non-null but

MongoDB, Is there a way to fix avoid duplicate values? findOneAndUpdate(filter, update, options, callback) fields: {Object|String} - Field selection. are true, mongoose will apply the defaults specified in the model's schema if a new� Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Mongoose findOneAndUpdate not working - node.js - html, I am trying to use 'findOneAndUpdate' in mongoose and the updated JS object I field and the _id:0 is for not returning the _id field since it is always displayed and I am not sure whether diagram is your model here, try with your Model, because i don't Also, new is set to true by default so you won't need the options dict. Mongoose's findOneAndUpdate() is slightly different from the MongoDB Node.js driver's findOneAndUpdate() because it returns the document itself, not a result object. As an alternative to the new option, you can also use the returnOriginal option.

I am trying to use the findOneAndUpdate hook with Mongoose (discussed in detail here), although I'm having some problems trying to set a value post update. For example: MySchema.findOneAndUpdate(

Comments
  • Solved : SInce we are updating a JSON, the payload must be in JSON format
  • I dont think thats the issue. I have other api calls like DELETE one (findOneAndDelete) , and im using request.params.hash.toString() , to identify the object , If i try to implement it in my current PUT, it wont work anyway. Your answer will log { hash: 'd6e0fdb404cb9779a34894b4809f492f1390216ef9d2dc0f2ec91f95cbfa89c9' } and wont update anything. It returns an error. And my alternative request.params.hash.toString() returns d6e0fdb404cb9779a34894b4809f492f1390216ef9d2dc0f2ec91f95cbfa89c9 and wont update anything, despite of using it in the delete method just fine
  • Theres not really any error, it just returns the same object without any change
  • Could you post your schema
  • I use a model const BlockModel = Mongoose.model('blocks', { //modelo blocks de la bd hash: String, height: Number, size: Number, time: Number })
  • @mouchin777 Updated my answer.
  • That doesnt seem to be the issue, it will return an error.
  • Theres not really any error message, it just gets caught by the 500 error code { "statusCode": 500, "error": "Internal Server Error", "message": "An internal server error occurred" }
  • can you post your postman object? in question you missed : after "time"
  • ``` { "size": 300, "time" : 2 } ``` , i send it with a PUT . The missed : is not the issue i misstyped it in the q