I am currently trying to update this MongoDB document with details from cloudinary. I have gone through so many similar questions here on stackoveflow but no solution worked for me, hence i am asking mine. Here is a copy of my schema file:
const mongoose = require('mongoose');
const CarSchema = new mongoose.Schema({
Name: {
type: String,
required: true
},
Model: {
type: String,
required: true
},
Year: {
type: String,
required: true
},
engine: {
type: String,
required: true
},
color: {
type: String
},
status: {
type: String,
enum: ['available', 'unavailable'],
default: 'available'
},
photos: [
{
imageUrl: {
type: String
},
publicId: {
type: String
}
}
]
});
module.exports = mongoose.model('Car', CarSchema);
Now here is a copy of my Router.js file
router.put('/upload/:id', isAuthUser, upload.single('image'), async (req, res) => {
// let car = await Car.findById(req.params.id);
try {
const result = await cloudinary.uploader.upload(req.file.path);
console.log(result);
// Updating thr car document
const updatedCar = await Car.updateOne(
{
_id: req.params.id
},
{
$push: {
'photos.$.imageUrl': result.url,
'photos.$.publicId': result.public_id
}
}
);
return res.status(200).json(updatedCar);
} catch (error) {
console.log(error.stack);
return res.status(500).json(error.stack);
}
});
Here is the error i keep getting:
MongoServerError: The positional operator did not find the match needed from the query.
at C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\operations\update.js:85:33
at C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\cmap\connection_pool.js:273:25
at handleOperationResult (C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\sdam\server.js:327:20)
at Connection.onMessage (C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\cmap\connection.js:215:9)
at MessageStream.<anonymous> (C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (node:events:527:28)
at processIncomingData (C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (C:\Users\userpc\Desktop\CAR-HIRE-APP\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
CodePudding user response:
The $push
stage is wrong:
{
$push: {
'photos.$.imageUrl': result.url,
'photos.$.publicId': result.public_id
}
}
$
is a positional operator, which refers to the index of a particular element in the array. You don't need it. Try this:
{
$push: {
'photos': {
$each: [
{
imageUrl: result.url,
publicId: result.public_id
}
]
}
}
}