Reputation: 43
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?
Upvotes: 0
Views: 29
Reputation: 259
You can use $push
at your query like:
User.findOneAndUpdate(
{ phone: "0912341234" },
{
$push: {
locations: {
location: {
latitude: 10,
longitude: 10,
},
status: "online",
},
},
},
{ new: true },
);
Upvotes: 1