Mongodb TypeError: vehicle.save is not a function - mongodb

When I perform a delete request, it returns an error stating that save is not a function
const Vehicle = require('../models/vehicle');
router.delete('/:id', async (req, res) => {
console.log('id: ', req.params.id);
const vehicle = await Vehicle.deleteOne({_id: req.params.id});
try {
vehicle.save();
res.send('ok');
} catch (error) {
console.log('err: ', error);
res.send(error);
}
});
vehicle's schema
const mongoose = require('mongoose');
const vehicle = new mongoose.Schema({
AID: {
type: Number,
required: true
},
OwnerName: {
type: String,
required: true
},
OwnerNIC: {
type: String,
required: true,
},
PhoneNo: {
type: String,
required: true
},
VehicleName: {
type: String,
required: true
},
EngineNo: {
type: String,
required: true
},
ChasisNo: {
type: String,
required: true
},
NoPlate: {
type: String,
required: true
},
RegFees: {
type: Number,
required: true
}
});
module.exports = mongoose.model('Vehicle', vehicle);

I can see some mistakes in your code.
Incorrectly wrapping the await with the try-catch block.
Irrelevant use of the mongoose save(). You don't need to use the save() method when performing a delete request.
Your code should be changed like this:
const Vehicle = require('../models/vehicle');
router.delete('/:id', async (req, res) => {
console.log('id: ', req.params.id);
try {
await Vehicle.deleteOne({_id: req.params.id});
res.send('Vehicle deleted.');
} catch (error) {
console.log('err: ', error);
res.send(error);
}
});

const Vehicle = require('../models/vehicle');
router.delete('/:id', async (req, res) => {
console.log('id: ', req.params.id);
await Vehicle.deleteOne({_id: req.params.id}).then((result) => {
console.log('Result: ', result);
if (result.n > 0) {
res.status(200).json({ message: "Vehicle Deleted" });
} else {
res.status(401).json({ message: "Error to delete " });
}
}).catch((error) => {
res.status(500).json({ message: "Not Delete" });
});
});

Related

How to update a user profile which has a property which is a ref in MongooseJS?

I have a User schema which has reference to a profile schema.
const UserSchema = new Schema(
{
_id: mongoose.Schema.Types.ObjectId,
email: {
....email props...
},
password: {
...password props...
},
profile: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Profile",
}],
},
);
const Profile = new Schema({
_user: {
type: Schema.Types.ObjectId, ref: 'User'
},
'displayName': {
type: String,
default: ''
},
'interestedActivities': ['Ping-pong'], <---- This bad boy/girl is an array
'memberSince': { type: Date, default: Date.now }
}
)
I'd like to create a route which can update the User properties AND the Profile properties in one shot—with a caveat one of the properties on the Profile model is an array!!!
I tried this....
handler
.use(auth)
.put((req, res, next) => {
emailValidator(req, res, next, 'email');
},
async (req, res, next) => {
await connectDB()
const {
profileDisplayName,
profileEmail,
interestedActivities } = req.body;
const update = {
email: profileEmail,
'profile.$.displayName': profileDisplayName,
'profile.$.interestedActivities': interestedActivities
}
const filter = { _id: req.user.id };
const updatedUser = await User.findOneAndUpdate(filter, update, { new: true })
try {
console.log("updatedUser ", updatedUser);
if (updatedUser) {
return res.status(200).send({
updatedUser,
msg: `You have updated your profile, good job!`
});
}
} catch (error) {
errorHandler(error, res)
}
})
export default handler;
My response is:
Status Code: 500 Internal Server Error
Cast to ObjectId failed for value "[
{
id: 'ae925393-0935-45da-93cb-7db509aedf20',
name: 'interestedActivities',
value: []
}
]" (type Array) at path "profile.$"
Does anyone know how I could also afford for the property which is an array?
Thank you in advance!

Updating array of objects in Mongoose

I can't handle updating array of objects in my database, tried many options but nothing worked. Im pretty sure that the answer is obvious, but I couldn't manage it since wednesday.
Here is my kitSchema:
const kitSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
kit: {
type: Array,
required: true,
},
profiles: {
type: Array,
required: true,
},
});
module.exports = mongoose.model("Kit", kitSchema);
All users have their own document, and there are also profiles in it. I want to update single profile by passing the id of user and id of profile.
Example of data:
_id: 1,
email: "abc#mail",
password: "abc",
profiles: [
{
id: 1,
name: John
},
]
And here's my latest solution which doesn't work:
router.put("/profile/:id", async (req, res) => {
let kit = await Kit.findById(req.params.id, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
});
try {
await kit.profiles.findOneAndUpdate(
{ id: req.body.id },
{ name: req.body.name },
{ new: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
} catch (err) {
res.status(400).json({ message: err });
}
});
Could you give me a hand with this?
As always, after days of trying I've got answer 10 minutes after asking question. Here's what I came up with:
router.put("/profile/:id", async (req, res) => {
await Kit.findOneAndUpdate(
{ _id: req.params.id, profiles: { $elemMatch: { id: req.body.id } } },
{
$set: {
"profiles.$.name": req.body.name,
"profiles.$.profilePicture": req.body.profilePicture,
},
},
{ new: true, safe: true, upsert: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
});

MongoDB - JSON schema validation

Can anyone please tell me where to place the $jsonSchema in the following code. Every time I test post my code returns the status(400) success: false.
All I'm trying to do is validator the title and description have been entered correctly.
import { connectToDatabase } from "../../../util/mongodb";
export default async (req, res) => {
const { method } = req;
const { db } = await connectToDatabase();
switch (method) {
case "GET":
try {
const products = await db.collection("products").find({}).toArray();
res.status(200).json({ success: true, data: products });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
case "POST":
try {
const product = await db
.collection("products")
.insertOne(req.body)
.runCommand({
collMod: "products",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["title", "description"],
properties: {
title: {
bsonType: "string",
description: "must be a string and is required",
unique: true,
},
description: {
bsonType: "string",
description: "must be a string and is required",
},
},
},
},
});
res.status(201).json({ success: true, data: product });
} catch (error) {
res.status(400).json({ sucess: false });
}
break;
default:
res.status(400).json({ dsucess: false });
break;
}
};

Create new subdocument in mongoose

What am I missing here? I want to add a sub document to the User schema I already have the schema predefined else where.
User.findById(req.body.id, function(err, user) {
if (err) return console.log(err);
reivews: [{
reviewer: req.body.name,
content: req.body.content
}]
user.save(function(err) {
if (err) console.log(err);
res.send('saved')
})
})
It's saying its saved but I don't see the review in the for the user with the id I tried to save to.
Schema
const Review = new Schema({
reviewer: String,
date : { type: Date, default: Date.now },
content : String,
isLive : { type: Boolean, default: false }
});
const User = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
reviews: [Review]
});
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('Review', Review);
module.exports = mongoose.model('User', User);
Please try this
User.findById(req.body.id, function(err, user) {
if (err) return console.log(err);
if (user.reviews === undefined || user.reviews.length == 0) {
user.reviews = [];
}
user.reviews.push({
reviewer: req.body.name,
content: req.body.content
});
user.save(function(err) {
if (err) console.log(err);
res.send('saved')
})
})
And ensure that data in user as per the defined Schema

How can I overwrite the entire document, instead of just updating the fields?

How can I overwrite the entire document, instead of just updating the fields?
Here is the method I use right now but doesn't work:
updateFilmTitle: function(req, res) {
var id = req.params.id;
console.log(id);
filmTitleModel.findByIdAndUpdate(id, req.body, {
overwrite: true
}, {
new: true
}, (error, response) => {
if (error) {
res.json(error);
console.error(error);
return;
}
console.log("filmTitle form has been updated!");
res.json(response);
console.log(response);
});
},
here how my model looks like,
var venueSchema = new Schema({
ticketServiceRequired: { type: Boolean, required: true },
filmSettings: {
type: {
filmContactName: { type: String, required: true },
filmSeatingAmount: { type: Number, required: true },
filmMediaDelivery: { type: Array, required: true },
filmRentalFee: {
price: { type: Number, required: true },
type: { type: String, required: true },
},
}
},
});
new and overwrite both are options, so it should be this:
filmTitleModel.findByIdAndUpdate(id, req.body, {
overwrite : true,
new : true
}, (error, response) => { ... });