Jacob Fuchs
Jacob Fuchs

Reputation: 357

Mongoosejs updating a subdocument

I am trying to push a subdocument position using $set operator. I have seen a similar SO thread Mongoose find/update subdocument. My model is showed below.

const mongoose = require('mongoose');

const positionSchema = new mongoose.Schema({

    posA: {
        type: Number,
    },

    posB: {
        type: Number,
    },

    date: {
        type: Date,
        default: Date.now
    }

}, { _id: false });

const LocationSchema = new mongoose.Schema({

    position: [positionSchema],

    username: {
        type: String,
        required: true
    },

}, { versionKey: false });

const Location = mongoose.model('Location', LocationSchema);

module.exports = Location;

For the first time a document is created in the database.

{
    "_id":{"$oid":"5e737eb7f0bdd67cf7521f6b"},
    "username":"username",
    "position":[{
        "posA":{"$numberInt":"123.855"},
        "posB":{"$numberInt":"45.8777"},
        "date":{"$date":{"$numberLong":"1584627688055"}}
    }]
}

In order to update the subdocument I have used this

const newPos = { posA: 76.66665, posB: 109.4455567 };

Location.findOneAndUpdate(
    { username: username},    // filter
    {
        "$set": {
            "position.$": newPos      // the new position added to the array
        }
    },
    (err, result) => {
        if (err) throw err;
        console.log(result);
});

Although, I receive an error and the subdocument is not added to the array

MongoError: The positional operator did not find the match needed from the query.

Is there a different approach?

Upvotes: 0

Views: 113

Answers (2)

henrip
henrip

Reputation: 190

Just take the '.$' off after "position" and it should work.

MongoDb doesn't find a match for positional operator because you haven't defined it in your query.

But you don't need to use positional operator in this case.

EDIT: Also if you dont want to replace the original array use: $push instead of $set

Upvotes: 0

Abdelrahman Hussien
Abdelrahman Hussien

Reputation: 505

inorder to push an item to an array try use $push instead of $set

Upvotes: 1

Related Questions