0

What im trying to do is to push the location and the status of the user in an array in a Schema. The reason I'm doing that is to store all the user locations in a schema(like a history location) When I create a location I use the method findOneAndUpdate().

controller/auth.js

exports.addLocation = asyncHandler(async (req, res, next) => {
  const {phone, locations, status} = req.body;

  const theLocation = await User.findOneAndUpdate(
    { phone },
    { locations, status },
    { new: false }
  )

  res.status(200).json({
      success: true,
      msg: "A location as been created",
      data: theLocation
  })
})

models/User.js

const UserSchema = new Schema({

  phone: {
    type: String,
    unique: true,
  },

  createdAt: {
    type: Date,
    default: Date.now
  },
  
  code: {
    type: Number,
    max: 4
  },

  fullName: {
    type:String
  },

  gender: {
    type:String
  },

  birthdate: {
    type:String
  },

  locations: [
    {
      location: {
        latitude: {type:Number},
        longitude: {type:Number},
      },

      status: {
        type: String
      },
    
      createdAt: {
        type: Date,
        default: Date.now,
      }
    }
  ],
});

So when a new item is stored, the previous one is deleted.

How can I save the previous item to another MongoDB field?

1 Answer 1

1

You can use $push at your query like:

User.findOneAndUpdate(
    { phone: "0912341234" },
    {
        $push: {
            locations: {
                location: {
                    latitude: 10,
                    longitude: 10,
                },
                status: "online",
            },
        },
    },
    { new: true },
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.