0
votes

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?

2
have you tried "$set": { "position": newPos // the new position added to the array } like this ? - Abdelrahman Hussien
and try to use updateOne instead - Abdelrahman Hussien
where is the username declared? - Abdelrahman Hussien
username is given from other part of the program. I have tried the solution you said above. it updates my subdocument but I did not explain well. I need to push a new subdocument in the array. I will edit my post - Jacob Fuchs
try to use $push instead of $set - Abdelrahman Hussien

2 Answers

1
votes

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

0
votes

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