Code in MongoDB triggers file is Producing a Customer.findOne() is not a function error - javascript

In order to be able to compare the pre and post-save version of a document, I am trying to lookup the document in a pre hook, and then use that to see what's changed in the doc in the post save hook.
But for some reason I'm getting a "Customer.findOne() is not a function" error. This doesn't make any sense to me because I've imported the model into this triggers file, and then, in my function I do this:
const Customer = require("../customer");
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
console.log("preSave firing with doc._id", doc._id); // this ObjectId logs correctly
if (!doc) return;
this.preSaveDoc = await Customer.findOne({ _id: doc._id }).exec();
console.log("this.preSaveDoc: ", this.preSaveDoc);
};
Again, this code produces an error:
"Customer.findOne() is not a function"
FYI, the relevant code in my Customer model looks like this:
let Schema = mongoose
.Schema(CustomerSchema, {
timestamps: true
})
.pre("count", function(next) {
next();
})
.pre("save", function(next) {
const doc = this;
trigger.preSave(doc);
next();
})
.post("save", function(doc) {
trigger.postSave(doc);
})
.post("update", function(doc) {
trigger.postSave(doc);
})
.post("findOneAndUpdate", function(doc) {
trigger.postSave(doc);
});
module.exports = mongoose.model("Customer", Schema);
What am I missing here? Why would this code produce this error on a very standard MongoDB operation?

This problem has already been solved.
If your mongoDb version is 3.6 or more, you can use change streams
Change streams lets you know what changed in your document. A background process runs in mongoDb which notifies your code an event(CREATE, UPDATE, DELETE) took place and passes you the document. You can filter on your fields to know the exact value.
You can refer this blog
This is a classic use case where change streams can be applied. Better than reinventing the wheel :)

Here is how you can get this to work. Instead of looking up the pre-saved/pre-transformed version of the document via Mongoose like this:
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
console.log("preSave firing with doc._id", doc._id); // this ObjectId logs correctly
if (!doc) return;
this.preSaveDoc = await Customer.findOne({ _id: doc._id }).exec();
console.log("this.preSaveDoc: ", this.preSaveDoc);
};
... look up the document this way:
// Get a version of the document prior to changes
exports.preSave = async function(doc) {
let MongoClient = await require("../../config/database")();
let db = MongoClient.connection.db;
db.collection("customers")
.findOne({ _id: doc._id })
.then(doc => {
this.preSaveDoc = doc;
});
};

Related

Model.create() from Mongoose doesn´t save the Documents in my Collection

I have created a sigle app with a Schema and a Model to create a Collection and insert some Documents.
I have my todoModel.js file:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const todoSchema = new Schema({
username: String,
todo: String,
isDone: Boolean,
hasAttachment: Boolean
});
const Todos = mongoose.model("Todo", todoSchema);
module.exports = Todos;
Then I have created a setUpController.js file with a sample of my Documents. Then I create a Model and I pass my sample of Documents and my Schema. I create a response to send tje result in JSON.
Everything good here, as I get the result in json when accessing to the route.
Here is the code:
Todos.create(sampleTodos, (err, results) => {
if (!err) {
console.log("setupTodos sample CREATED!")
res.send(results);
}
else {
console.log(`Could not create the setupTodos Database sample, err: ${err}`);
}
});
My problem is that this Documents don´t get saved in the collection !! When I access to the database, nothing is there.
This is my app.js file:
mongoose.connect("mongodb://localhost:27017/nodeTodo")
.then(connection => {
app.listen(port);
})
.catch(err => {
console.log(`Could not establish Connection with err: ${err}`);
});
Could anyone help me please ?
Thank you
Try creating an instance and making the respective function call of that instance. In your case, save the document after creating an instance and it works like a charm.
const newTodos = new Todos({
username: "username",
todo: "todos",
isDone: false,
hasAttachment: flase
});
const createdTodo = newTodos.save((err, todo) => {
if(err) {
throw(err);
}
else {
//do your staff
}
})
after the collection is created you can use the function inserMany to insert also a single document the function receives an array of objects and automatically saves it to the given collection
example:
Pet = new mongoose.model("pet",schemas.petSchema)
Pet.insetMany([
{
//your document
}])
it will save only one hardcoded document
I hope it was helpful

is there a way to automatically update everything in a mongoose document?

For example I want to update a mongoose document in a put request, I have to do this:
app.put('/update', async(req,res) => {
try{
const product = await Product.findById(req.body.id)
product.name = req.body.name
product.price = req.body.price
procut.discount = req.body.discount
// etc...
await product.save()
res.json(product)
}catch(e){
res.json({message: "Error updating the product"})
}
})
I'm asking if there is another faster and developer friendly way of updating products instead of typing each of the document properties and equal them to the req.body.[property]?
You can try the following for object merging
Object.assign(product, req.body)
note: i haven't tried with mongoose collection
You can use updateMany or findOneAndUpdate model methods, but it is more advisable to use .save()
https://mongoosejs.com/docs/api.html#model_Model.updateMany
https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
If you want to .save() to look cleaner, you can do like this:
async updateEntity(payload) {
const keysToUpdate = Object.keys(payload)
if (keysToUpdate.length === 0) {
throw new Error('Update payload must not be empty!')
}
const entity = await entityModel.findOne({ _id: redirect })
keysToUpdate.forEach((key) => {
entity[key] = payload[key]
})
await entity.save()}

Mongoose: save() is not a function when using find() and atributing value to variable

This is the basic structure of the Schema I am working with using mongoose:
const User = {
uid: {
type: String
},
routes: {
type: Array
}
}
In my application there is a POST to /route, in which uid and a new route are provided as "body parameters". In order to add to the routes array, I wrote a code similar to this (the only diference is that I check if the route already exists):
var user = await User.find({uid: uid}) // user is found, as expected
user[0].routes.push(route //parameter)
user.save()
When a POST request is made, though, it throws an error:
TypeError: user.save is not a function
What am I doing wrong?
user in your code is an array of documents
so you'll have mongo documents inside that array
you can't do array.save, you've to do document.save
await user[0].save()
var user = await User.find({uid: uid}) // user is found, as expected
if (user && user.length) {
user[0].routes.push(route //parameter)
await user[0].save(); // save the 1st element of the object
}
if your query returns only 1 record better use https://mongoosejs.com/docs/api.html#model_Model.findOne
var user = await User.findOne({uid: uid}) // user is found, as expected
if (user) {
user.routes.push(route //parameter)
await user.save(); // save the 1st element of the object
}
if you need to find only one specific user you should use findOne function instead
User.findOne({uid: uid})
.then(
(user) => {
user[0].routes.push(route //parameter);
user.save();
},
(err) => {
console.error(err);
}
)
I think bulkSave() can be what you're looking for:
var user = await User.find({uid: uid}
enter code user[0].routes.push(route //parameter)
await User.bulkSave(user)

check if object in array of objects - javascript

I know i have to use some but for some reason i cant seem to get it right. i have a collection in my mongodb database of posts. each post has an array of objects named "likes" that references the users that liked this post. so in my backend i want to check if the user exists in the likes array of the post. if it does not exist then like the post, else return with an appropriate message on my react frontend. The code i will include always returns false from some so a user can like a post infinite times.
exports.postLike = async (req, res, next) => {
const postId = req.query.postId;
const userId = req.query.userId;
console.log('postId: ' + postId);
try{
const post = await Post.findById(postId).populate('creator').populate('likes');
const user = await User.findById(userId);
if (!post.likes.some(post => post._id === user._id)){
post.likes.push(user);
console.log('liked a post');
const result = await post.save();
res.status(200).json({ message: 'Post liked!', post: result });
} else {
console.log('Post already liked!');
res.status(200).json({ message: 'Post already liked!', post: post });
}
}catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
i clearly haven't understood, yet, how some works so if you can help that would be great. also if you have any other solution that would be good in this case then please post it. i tried some random codes with indexOf and includes for checking but it didn't work either. i am not sure which is the right way to check if the user object is included in the "likes" array of objects. i would prefer not to write any function of my own to check this, i want to do it using an existing function/method provided by javascript.
Going to offer a different route here. You are fetching all the data including a join to the creator and likes just to add a like to the collection. This is a little wasteful and can be achieved by just doing an update and use $addToSet which will add the like if it does not exist.
You then just check nModified in the result to know if it was added or not. So you can have:
const result = await Post.updateOne(
{
id: 1
},
{
$addToSet: {
likes: {
userId: mongoose.Types.ObjectId(req.query.userId)
}
}
}
);
console.info(result.nModified === 1);
Alternatively, you can use some as follows using === to compare type and value:
posts.likes.some(like => like.userId.toString() === req.query.userId)
MongoDB.ObjectId is a wrapper around a primitve, just like Number or Boolean. And just like
new Boolean(true) === new Boolean(true)
will be false, your comparison will fail too. You have to take out the primitive for comparison:
post._id.valueOf() === user._id.valueOf()

Express and Mongoose-failing to update an object

I'm trying to update an object by assigning it a new field, which is defined in the schema, like this:
exports.updatePlot = async (req, res) => {
let modifications = {};
modifications = Object.assign(modifications, req.body.props);
const id = modifications.id;
try {
const updatedPlot = await Plot.findByIdAndUpdate(
id,
{ $set: modifications },
{ new: true }
);
console.log(('updated plot saved:', updatedPlot));
res.json({
updatedPlot
});
} catch (e) {
console.log('error', e);
return res.status(422).send({
error: { message: 'e', resend: true }
});
}
};
This works when I modify existing fields. However, when I try to add a new field (which is defined in the Mongoose schema, but does not exist in the object in the database), it fails. Meaning, there is no error, but the new field is not added.
Any ideas?
According to mongoose documentation of findByIdAndUpdate
new: bool - true to return the modified document rather than the original. defaults to false
upsert: bool - creates the object if it doesn't exist. defaults to false.
You are mistaking new with upsert
Moreover as #Rahul Sharma said and looking at mongoose documentation example, you do not need to use $set

Categories

Resources