Mongoose update subdocument of subdocument - javascript

My schema definition as below. UserSchema has embedded Cards which in turn has many transactions..
var TransactionSchema = new Schema({
merchantName: String,
transactionTime: Date,
latitude: Number,
longitude: Number,
amount: Number
});
var CardSchema = new Schema({
cardIssuer: String,
lastFour: String,
expirationDate: String,
transactions : [TransactionSchema]
});
/*
* ...User Schema...
*/
var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String,
imageURL: String,
phoneNumber: String,
card: [CardSchema]
});
I want to add a transaction to the card already in the userschema but I am not sure how to do this in mongoose / mongodb
I identify the user and card as follows..
The api call goes through the auth middleware first
function isAuthenticated() {
return compose()
// Validate jwt
.use(function(req, res, next) {
// allow access_token to be passed through query parameter as well
if(req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function(req, res, next) {
User.findById(req.user._id, function (err, user) {
if (err) return next(err);
if (!user) return res.send(401);
req.user = user;
next();
});
});
}
// This is update based on Neil's answer below...
exports.create = function(req, res) {
//var userItem = req.user;
//console.log(userItem._id);
//console.log(req.params.card);
Transaction.create(req.body, function(err, transaction){
console.log(transaction);
//id = mongoose.Types.ObjectId;
User.findOneAndUpdate({"card._id":id(req.params.card)},{
// $set : {
// role: 'user1'
// } ---- this update operation works!!
"$push": {
"card.$.transactions": transaction
} // -- this update operation causes error ...
}, function(err,user) {
// updated document here
console.log('err' + err + " user " + user) ;
return res.json(200, user);
}
)
// }
// })
})
};

Adding new elements to an inner array is not difficult, as all you really need to do is match the position of the outer array to update in your query and then apply the positional $ operator in the update portion.
var transaction; // and initialize as a new transaction
User.findOneAndUpdate(
{ "card._id": cardId },
{
"$push": {
"card.$.transactions": transaction.toObject()
}
},
function(err,user) {
// updated document here
}
)
So that is straightforward for $push operations. But be careful that you only ever want to $push or $pull as trying to update at a position of in "inner" array is not possible since the positional operator will only contain the first match, or the position in the "outer" array.

Related

Mongoose - When returning all items from a collection (with no search param) the returned items from the collection do not contain their mongo _id

I am having a bit of an issue with Mongoose/MongoDB this afternoon. I have a situation where I need to return all items from a collection, and doing so means that I do not pass in any search params to mongoose.find().
This is the controller that handles the get all request:
exports.get_all_posts = async (req, res, next) => {
const { params } = req;
const { sortby } = params;
//Sortby param takes two arguments for now: most_recent, oldest
try {
const getAllPosts = await BlogPost.find({}, { _id: 0 });
console.log(getAllPosts);
if (!getAllPosts) throw new Error('Could not get blog posts.');
res.json({
posts: date_.sort(getAllPosts, sortby)
});
} catch (error) {
next(error);
}
};
This is particularly where I think the issue is coming from:
const getAllPosts = await BlogPost.find({}, { _id: 0 });
I am passing an empty search parameter and then removing the _id so that it doesn't throw an error telling me that I need to provide the _id.
However I still need to be able to pull in all of the posts. My items from this collection return as normal, just without their _id's.
Here is my model for the blog posts:
const mongoose = require('mongoose');
const BlogPostSchema = new mongoose.Schema({
date: {
type: Date,
required: true
},
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
likes: {
type: Number,
required: false
},
post_body: {
type: String,
required: true
},
description: {
type: String,
required: true
},
tags: [
{
type: String,
required: false
}
],
featuredImage: {
type: String,
required: false
},
draft: {
type: Boolean,
required: true
}
});
module.exports = mongoose.model('BlogPost', BlogPostSchema);
One thing to note is that I have not defined an _id. Mongoose automatically adds in the _id field before saving a schema, so I think it is okay without it, as it has been in the past.
Thanks in advance for reading and any input!
Just as Joe has commented, { _id: 0 } as the second parameter is making your query not return the _id field.
Also as he said, there should be no problem whatsoever with using find({}).
Since other than what has already been stated, I couldn't figure out any mistake in the code snippets you provided, I guess this error could be coming from somewhere else in your project.
exports.get_all_posts = async (req, res, next) => { const { params } = req; const { sortby } = params;
try { const getAllPosts = await BlogPost.find({}); console.log(getAllPosts); if (!getAllPosts) throw new Error('Could not get blog posts.'); res.json({ posts: date_.sort(getAllPosts, sortby) }); } catch (error) { next(error); } };
no need to {_id:0} in the find() method because this method retrieve all the documents in the db collection

Mongoose - Model.deleteOne() is deleting the entire collection instead of a single document

I have a User model that contains an array of customers. I want to delete a specific customer based on the customer _id. From what I've read in the Mongoose docs, I should use Model.deleteOne to delete a single document.
Here is my attempt
User Schema (it's been shortened for brevity):
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
username: {
type: String,
default: ''
},
password: {
type: String,
default: '',
},
registerDate: {
type: Date,
default: Date.now()
},
customer: [{
name: {
type: String,
default: '',
},
email: {
type: String,
default: 'No email name found'
},
fleet: [{
unitNumber: {
type: String,
default: 'N/A',
}
}]
}]
});
module.exports = mongoose.model('User', UserSchema);
Here is a look at the route and controller:
const express = require('express');
const router = express.Router();
const customer_controller = require('../../controllers/customers');
router.delete('/customers/:custid', customer_controller.customer_remove);
module.exports = router;
And finally the controller:
exports.customer_remove = (req, res) => {
const { params } = req;
const { custid } = params;
User.deleteOne({ 'customer._id': custid }, (err) => {
if (err)
throw err;
else
console.log(custid, 'is deleted');
});
};
From what I thought, User.deleteOne({ 'customer.id': custid }) would find the customer _id matching the custid that is passed in via the req.params. When I test this route in Postman, it deletes the entire User collection that the customer is found in, instead of just deleting the customer. Can I get a nudge in the right direction? I feel like I am close here (or not lol).
deleteOne operates at the document level, so your code will delete the first User document that contains a customer element with a matching _id.
Instead, you want update the user document(s) to remove a specific element from the customer array field using $pull. To remove the customer from all users:
User.updateMany({}, { $pull: { customer: { _id: custid } } }, (err) => { ...
Using Mongoose you can do this:
model.findOneAndUpdate({ 'customer._id': custid }, {$pull: { $pull: {
customer: { _id: custid } }}, {new: true}).lean();
Removing subdocs.
Each sub document has an _id by default. Mongoose document arrays have a special id method for searching a document array to find a document with a given _id.
Visit: https://mongoosejs.com/docs/subdocs.html
parent.children.id(_id).remove();
Use async-await, may be that will work.
exports.customer_remove = async (req, res) => {
const { params } = req;
const { custid } = params;
try {
await User.deleteOne({ 'customer._id': custid });
console.log(custid, 'is deleted');
} catch (err) {
throw err;
}
};

querying mongodb collection for regex using mongoose

I am trying to query using regex for mongoose, I have seen other posts which have similiar suggestions but I still couldn't figure out, and also getting new errors instead of just getting a null document back.
I am trying to query value contains instead of the need of the exact to get results
for my route, I have something like this
router.get('/:name/:value', (req, res, next) => {
const o = {};
const r = `.*${req.params.value}.*`;
// the above gives me error such as CastError: Cast to string failed for value "{ '$regex': '.*y.*' }" at path "username" for model "Model"
o[req.params.name] = { $regex: { $regex: r }, $options: 'i' };
Model.find(o, (err, doc) => {
if (err) return next(err);
res.send('success');
});
});
can someone give me a hand where I have been doing wrong?
Thanks in advance for any help.
Suppose below is your Model
//Employee.js
import mongoose from 'mongoose';
const Employee = mongoose.Schema({
Name: { type: String, default: "" },
Age: { type: Number, default: 0 },
Email: { type: String, default: "" },
}, { collection: 'Employee' });
export default mongoose.model('Employee', Employee);
Your router must be like below
var Employee = require('../path/to/Employee.js');
router.get('/name/:value', (req, res, next) => {
let query = {
Name: {
$regex: req.params.value,
$options: "i"
}
};
Employee.find(query, (err, docs) => {
if (err) return next(err);
console.log("Documents-->", docs)
res.send('success');
});
});
You no need to give separate param for name just do query like above

unhandled promise rejection warning - couldn't store into database

Data comming from req is store in Comment collection but it is not store in Product collection and i'll get an error message
app.post("/products/:id/comments", function(req, res) {
//lookup campground using ID
Product.findById(req.params.id, function(err, product) {
if (err) {
console.log(err);
res.redirect("/products");
} else {
Comment.create(req.body.comment, function(err, comment) {
if (err) {
console.log(err);
} else {
console.log("aaaaaa");
product.comments.push(comment);
console.log("bbbbbb");
product.save();
console.log("cccccc");
res.redirect('/products/' + product._id);
}
});
}
});});
and following is Product
var mongoose = require("mongoose"),
productSchema = new mongoose.Schema({
name: String,
img: String,
price: Number,
desc: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}],
created: {
type: Date,
default: Date.now()
}});module.exports = mongoose.model("Product", productSchema);
and this is Comment Schema
var mongoose = require("mongoose"),
commentSchema = mongoose.Schema({
text: String,
author: String
});module.exports = mongoose.model("Comment", commentSchema);
and i got following output :-
enter image description here
so it's store in commentSchema but it's not store in product.comments and when i run site that also redirect to products/:id, what i'm missing to store comment into database ??
If you don’t pass a callback function to save() then it will return a promise.
Therefore, you are getting the error as you have not added a catch.
Try passing a callback to save():
// ...
product.save(function(err, result) {
if (err) {
// Handle error
}
console.log("cccccc");
res.redirect('/products/' + product._id);
})

Populate Query Options with Async Waterfall

I'm trying mongoose populate query options but i don't know why the query options doesn't work.
I have user schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
username: { type: String, required: true },
email: { type: String },
name: { type: String },
address: { type: String }
},
{ timestamps: true }
);
module.exports = mongoose.model('User', UserSchema);
and feed schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FeedSchema = new Schema(
{
user: { type: Schema.ObjectId, ref: 'User' },
notes: { type: String, required: true },
trx_date: { type: Date },
status: { type: Boolean, Default: true }
},
{ timestamps: true }
);
FeedSchema.set('toObject', { getters: true });
module.exports = mongoose.model('Feed', FeedSchema);
I want to find all feed by user id, i used async waterfall like the following code:
async.waterfall([
function(callback) {
User
.findOne({ 'username': username })
.exec((err, result) => {
if (result) {
callback(null, result);
} else {
callback(err);
}
});
},
function(userid, callback) {
// find user's feed
Feed
.find({})
// .populate('user', {_id: userid._id}) <== this one also doesn't work
.populate({
path: 'user',
match: { '_id': { $in: userid._id } }
})
.exec(callback);
}
], function(err, docs) {
if (err) {
return next(err);
}
console.log(docs);
});
With above code, i got all feeds, and it seems like the query option do not work at all, did i doing it wrong ?
Any help would be appreciate.
Not sure why you are looking to match "after" population when the value of _id is what is already stored in the "user" property "before" you even populate.
As such it's really just a simple "query" condition to .find() instead:
async.waterfall([
(callback) =>
User.findOne({ 'username': username }).exec(callback),
(user, callback) => {
if (!user) callback(new Error('not found')); // throw here if not found
// find user's feed
Feed
.find({ user: user._id })
.populate('user')
.exec(callback);
}
], function(err, docs) {
if (err) {
return next(err);
}
console.log(docs);
});
Keeping in mind of course that the .findOne() is returning the whole document, so you just want the _id property in the new query. Also note that the "juggling" in the initial waterfall function is not necessary. If there is an error then it will "fast fail" to the end callback, or otherwise pass through the result where it is not. Delate "not found" to the next method instead.
Of course this really is not necessary since "Promises" have been around for some time and you really should be using them:
User.findOne({ "username": username })
.then( user => Feed.find({ "user": user._id }).populate('user') )
.then( feeds => /* do something */ )
.catch(err => /* do something with any error */)
Or indeed using $lookup where you MongoDB supports it:
User.aggregate([
{ "$match": { "username": username } },
{ "$lookup": {
"from": Feed.collection.name,
"localField": "_id",
"foreignField": "user",
"as": "feeds"
}}
]).then( user => /* User with feeds in array /* )
Which is a bit different in output, and you could actually change it to look the same with a bit of manipulation, but this should give you the general idea.
Importantly is generally better to let the server do the join rather than issue multiple requests, which increases latency at the very least.

Categories

Resources