How to make auto suggestion in mean stack - mongodb

I have this code :
async function getUserByArtistName(artistName) {
let userDB = await User.find(
{$text: { $search: artistName}},
(err, res) => {
if(err){
console.log("ERROR : ")
console.log(err)
} else {
console.log(res)
}
});
return userDB;
}
and i need to find user where User.artistName contains * artistName *. is it possible ?
Thank you verry much !

the answer :
async function getUserByArtistName(artistName) {
let userDB = await User.find(
{ artistName: { $regex: artistName, $options: "i" } },
(err, res) => {
if(err){
console.log("ERROR : ")
console.log(err)
} else {
console.log(res)
}
});
return userDB;
}

Related

findByIdAndUpdate do not update document

I am trying to update a field to the document with findByIdAndUpdate. The field I am trying to update is defined in the Bar Model. And I can also assure that req.body.bookId has a valid id.
Here's how my request looks,
app.patch("/foo", async (req, res) => {
try {
await validateId(req.body.bookId);
let doc = await Bar.findByIdAndUpdate(
req.body.bookId,
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (err) {
console.log(err);
}
});
Bar schema,
const mongoose = require("mongoose");
const barSchema = mongoose.Schema({
bookId: {
type: String,
unique: true,
},
DateT: {
type: Date,
default: null,
},
});
module.exports = mongoose.model("Bar", barSchema);
use updateOne, when you use async don't use .then() use try/catch
test it:
app.patch("/foo", async (req, res) => {
try {
let doc = await Bar.updateOne(
{ bookId : req.body.bookId },
{ DateT: Date.now() },
{ new: true }
);
res.send(doc);
} catch (error) {
console.log(error);
}
});
app.patch("/foo", async (req, res) => {
await Bar.findByIdAndUpdate(
req.body.bookId,
{ DateT: Date.now()},
(err, docs) => {
if (err) {
console.log(err);
} else {
res.send(docs);
}
}
);
});

How do I use populate with callbacks?

User model
const Schema = mongoose.Schema
const userSchema = new Schema({
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
posts:[{ type: Schema.Types.ObjectId, ref: "Posts" }]
}, { timestamps: true })
Post model
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: { type: String, required: true },
content: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
}, { timestamps: true }
endpoint for getting all posts with all users information
listPostsWithUsers: (req, res, next) => {
Post.find({}, (error, posts) => {
if (error) {
return res.status(500).json({ error: "something went wrong" })
} else if (!posts) {
return res.status(400).json({ msg: "sorry no posts" })
} else if (posts) {
return res.status(200).json({ posts })
}
})
}
The output should be the returned posts with the user object so that I can identify which post the user has posted.
Now, my question is how do I apply populate() method in the above endpoint. Mostly all examples are with exec() function but I've seen no example with callbacks. It's kind of a syntax problem.
Thank you.
Update#1: The result I'm getting currently.
{
"posts": [
{
"_id": "5e65cce5ebddec0c5cc925ab",
"title": "Neil's Post",
"content": "post by neil.",
"createdAt": "2020-03-09T04:58:13.900Z",
"updatedAt": "2020-03-09T04:58:13.900Z",
"__v": 0
},
{
"_id": "5e65cd32ebddec0c5cc925ad",
"title": "Slash's post",
"content": "post by slash.",
"createdAt": "2020-03-09T04:59:30.180Z",
"updatedAt": "2020-03-09T04:59:30.180Z",
"__v": 0
},
{
"_id": "5e65f430a989612916636e8d",
"title": "Jimmy's post",
"content": "post by jimmy",
"createdAt": "2020-03-09T07:45:52.664Z",
"updatedAt": "2020-03-09T07:45:52.664Z",
"__v": 0
}
]
}
Update#2
users collection.
{
"users": [
{
"posts": [],
"_id": "5e65ccbeebddec0c5cc925aa",
"username": "Neil",
"email": "neily888#gmail.com",
"password": "$2b$10$AHHRKuCX3nakMs8hdVj0DuwD5uL0/TJwkJyKZYR/TXPTrIo9f80IW",
"createdAt": "2020-03-09T04:57:35.008Z",
"updatedAt": "2020-03-09T04:57:35.008Z",
"__v": 0
},
{
"posts": [],
"_id": "5e65cd0eebddec0c5cc925ac",
"username": "Slash",
"email": "slash938#gmail.com",
"password": "$2b$10$QQX/CFJjmpGdBAEogQ4XO.1e1ZowuPCX7pJcHTUav7NfatGgp6sa6",
"createdAt": "2020-03-09T04:58:54.520Z",
"updatedAt": "2020-03-09T04:58:54.520Z",
"__v": 0
},
{
"posts": [],
"_id": "5e65f408a989612916636e8c",
"username": "Jimmy",
"email": "jimmy787#gmail.com",
"password": "$2b$10$/DjwWYIlNswgmYt3vo7hJeNupfBdFGe7p77uisYUViKv8IdhasDC.",
"createdAt": "2020-03-09T07:45:12.293Z",
"updatedAt": "2020-03-09T07:45:12.293Z",
"__v": 0
}
]
}
Update#3:
usersController
const User = require("../models/User")
module.exports = {
createUser: (req, res) => {
User.create(req.body, (err, createdUser) => {
if (err) console.log(err)
res.json({createdUser})
})
},
listUsers: (res) => {
User.find({}, (err, users) => {
if (err) console.log(err)
res.json({users})
})
},
getUser: (req, res) => {
User.findById(req.params.id, (err, user) => {
if (err) console.log(err)
return res.json({user})
})
},
updateUser: (req, res) => {
const user = {
username: req.body.username,
email: req.body.email,
password: req.body.password
}
User.findOneAndUpdate(req.params.id, user, { new: true }, (err, updatedUser) => {
if (err) console.log(err)
res.json({updatedUser})
})
},
deleteUser: (req, res) => {
User.findByIdAndDelete(req.params.id, (err, deleteduser) => {
if (err) console.log(err)
return res.status(200).json({ user: deleteduser })
})
}
}
postsController
const Post = require("../models/Post")
module.exports = {
createPost: (req, res) => {
const data = {
title: req.body.title,
description: req.body.description,
}
Post.create(data, (err, newPost) => {
if (err) console.log(err);
return res.status(200).json({ newPost })
})
},
listPosts: (res) => {
Post.find({}, async (err, posts) => {
if (err) console.log(err);
posts = await Post.populate(posts, {
path: "user",
model: "User"
})
return res.status(200).json({ posts })
})
},
findPost: (req, res) => {
Post.findById(req.params.id, (err, post) => {
if (err) console.log(err);
return res.json({ post })
}
)
},
updatePost: (req, res) => {
const post = {
title: req.body.title,
description: req.body.description
}
Post.findByIdAndUpdate(req.params.id, post, { new: true },(err, updatedPost) => {
if (err) console.log(err);
return res.status(200).json({ updatedPost })
})
},
deletePost: (req, res) => {
Post.findByIdAndDelete(req.params.id, (err, deletedPost) => {
if (err) console.log(err);
return res.status(200).json({ deletedPost })
})
}
}
Update#4
router.get("/posts/:id", usersController.getUserPosts) `
getUserPosts: (req, res) => {
User.findById(req.params.id, async (err, user) => {
if (err) {
return res.status(500).json({ error: "Server error" })
} else if (!user) {
return res.status(400).json({ error: "No user" })
} else if (user) {
user = await User.populate("user", {
path: "posts",
model: "Post"
})
return res.status(200).json({ user })
}
})
}
I suggest you to use mongoose populate.
listPostsWithUsers : (req, res, next) => {
Post.find({}).populate('user').exec(function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
})
}
You can refer this official mongoose populate document
You can even populate as many fields required by using populate as
populate([{ path: 'user' }, { path: 'book', select: { author: 1 } }])
with the help of select in populate, you can project the required fields (get only those fields from populated collection.)
Edit 1
createPost: (req, res) => {
const data = {
title: req.body.title,
description: req.body.description,
user: req.user._id,
}
Post.create(data, (err, newPost) => {
if (err) console.log(err);
return res.status(200).json({ newPost })
})
You will need to add user field in post while creating.
take user id from token or from query and you would be good to go.
Edit 2
getUserPosts: (req, res) => {
User.findById(req.params.id).populate([{ path: 'posts' }])
.exec(function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
}
You are finding data in user module and you want to populate post data, so you just need to say which field you want to populate as you have already defined on field which model to refer by adding ref with that field in mongoose schema.
getUserPosts: (req, res) => {
User.findById(req.params.id, async (err, user) => {
if (err) {
return res.status(500).json({ error: "Server error" })
} else if (!user) {
return res.status(400).json({ error: "No user" })
} else if (user) {
user = await User.populate("posts")
return res.status(200).json({ user })
}
})
}
This should also work for you.
You can do that after getting the posts as:
listPostsWithUsers: (req, res, next) => {
Post.find({}, async (error, posts) => {
if (error) {
return res.status(500).json({ error: "something went wrong" })
} else if (!posts) {
return res.status(400).json({ msg: "sorry no posts" })
} else if (posts) {
posts = await Post.populate(posts, {
path: 'user',
model: 'User'
});
return res.status(200).json({ posts })
}
})
}

Mongoose update only the values that have changed

I have a PUT route to update value. I am hitting this route from two places. One is sending information about details and one about completed. The problem is that mongoose is updating booth even though it gets value from only one.
So if I send information about completed that it is true and latter I hit this route with new details (that dont have completed value) it will update completed also to false. How do I update just the value that was changed?
router.put('/:id', (req, res) => {
Todo.findOne({_id:req.body.id}, (err, foundObject) => {
foundObject.details = req.body.details
foundObject.completed = req.body.completed
foundObject.save((e, updatedTodo) => {
if(err) {
res.status(400).send(e)
} else {
res.send(updatedTodo)
}
})
})
})
EDIT:
Thanks to Jackson hint I was managed to do it like this.
router.put('/:id', (req, res) => {
Todo.findOne({_id:req.body.id}, (err, foundObject) => {
if(req.body.details !== undefined) {
foundObject.details = req.body.details
}
if(req.body.completed !== undefined) {
foundObject.completed = req.body.completed
}
foundObject.save((e, updatedTodo) => {
if(err) {
res.status(400).send(e)
} else {
res.send(updatedTodo)
}
})
})
})
const updateQuery = {};
if (req.body.details) {
updateQuery.details = req.body.details
}
if (req.body.completed) {
updateQuery.completed = req.body.completed
}
//or
Todo.findOneAndUpdate({id: req.body.id}, updateQuery, {new: true}, (err, res) => {
if (err) {
} else {
}
})
//or
Todo.findOneAndUpdate({id: req.body.id}, {$set: updateQuery}, {new: true}, (err, res) => {
if (err) {
} else {
}
})
Had a function similar to this my approach was this
const _ = require('lodash');
router.put('/update/:id',(req,res, next)=>{
todo.findById({
_id: req.params.id
}).then(user => {
const obj = {
new: true
}
user = _.extend(user, obj);
user.save((error, result) => {
if (error) {
console.log("Status not Changed")
} else {
res.redirect('/')
}
})
}).catch(error => {
res.status(500);
})
};
Taking new : true as the value you updating
It gets kinda ugly as the fields to be updated get increased. Say 100 fields.
I would suggest using the following approach:
try {
const schemaProperties = Object.keys(Todo.schema.paths)
const requestKeys = Object.keys(req.body)
const requestValues = Object.values(req.body)
const updateQuery = {}
// constructing dynamic query
for (let i = 0; i < requestKeys.length; i++) {
// Only update valid fields according to Todo Schema
if ( schemaProperties.includes(requestKeys[i]) ){
updateQuery[requestKeys[i]] = requestValues[i]
}
}
const updatedObject = await TOdo.updateOne(
{ _id:req.params.idd},
{ $set: updateQuery }
);
res.json(updatedObject)
} catch (error) {
res.status(400).send({ message: error });
}

Why is forEach statement running more times than expect

I have the following function which is not working as expected for example I would like to create 24-irds and 3-smallparts, but instead I'm getting 24-irds and 72-smallparts. It seems like the smallparts forEach is iterrating the number of irds instead of smallparts. Any ideas why?
Thanks in advance
exports.pickup = function (req, res) {
async.waterfall([
function (callback) {
var order = createOrder(req);
callback(null, order);
},
function (order, callback) {
if (req.body.irds.length > 0) {
_(req.body.irds).forEach(function (n) {
var receiver = new Receiver(n);
receiver.order = order._id;
receiver.company = req.user.company;
receiver.user = req.user;
receiver.date = req.body.date;
receiver.location = req.user.location;
order.receivers.push(receiver._id);
receiver.save(function (err) {
callback(null, order);
if (err) {
console.log('error receiver exists');
}
});
});
} else {
callback(null, order);
}
},
function (order, callback) {
if (req.body.smallParts.length > 0) {
_(req.body.smallParts).forEach(function (n) {
var now = new Date();
var query1 = {'_id': req.user.company, 'products.product': n.product};
var query2 = {'_id': req.user.company};
var update1 = {
$inc: {
'products.$.quantity': n.quantityRequested,
'products.$.quantityOnhand': n.quantityRequested
},
'products.$.updated': now,
'products.$.lastPickUp.date': now,
'products.$.lastPickUp.quantity': n.quantityRequested
};
var update2 = {
$push: {
'products': {
'product': n.product,
'quantity': n.quantityRequested,
'quantityOnhand': n.quantityRequested,
'updated': now,
'lastPickUp.date': now,
'lastPickUp.quantity': n.quantityRequested
}
}
};
var options = {upsert: true};
Companies.findOneAndUpdate(query1, update1, function (err, doc) {
if (!doc) {
Companies.findOneAndUpdate(query2, update2, function (err, doc) {
if (err) {
throw err;
}
});
}
});
//save smallparts
n._id = new ObjectId();
var smallPart = new SmallPart(n);
smallPart.order = order._id;
smallPart.quantity = n.quantityRequested;
smallPart.company = req.user.company;
smallPart.user = req.user;
smallPart.location = req.user.location;
smallPart.date = req.body.date;
order.smallParts.push(smallPart._id);
smallPart.save(function (err) {
callback(null, order);
if (err) {
console.log(err);
}
});
})
} else {
callback(null, order)
}
},
function (order, callback) {
order.location = req.user.location;
order.company = req.user.company;
order.save(function (err) {
callback(null, 'done');
if (err) {
console.log(err);
}
});
}
], function (err) {
if (!err) {
res.status(200).json();
} else {
console.log(err);
}
});
};
I managed to figure out.
exports.pickup = function (req, res) {
var order = createOrder(req);
order.location = req.user.location;
order.company = req.user.company;
order.type = 'pickup';
async.series([
function (callback) {
if (req.body.irds.length > 0) {
_(req.body.irds).forEach(function (n) {
var receiver = new Receiver(n);
receiver.order = order._id;
receiver.company = req.user.company;
receiver.user = req.user;
receiver.date = req.body.date;
receiver.location = req.user.location;
order.receivers.push(receiver._id);
receiver.save(function (err) {
if (err) {
console.log('error saving receiver');
}
});
});
}
callback(null);
},
function (callback) {
if (req.body.smallParts.length > 0) {
_(req.body.smallParts).forEach(function (n) {
var now = new Date();
var query1 = {'_id': req.user.company, 'products.product': n.product};
var query2 = {'_id': req.user.company};
var update1 = {
$inc: {
'products.$.quantity': n.quantityRequested,
'products.$.quantityOnhand': n.quantityRequested
},
'products.$.updated': now,
'products.$.lastPickUp.date': now,
'products.$.lastPickUp.quantity': n.quantityRequested
};
var update2 = {
$push: {
'products': {
'product': n.product,
'quantity': n.quantityRequested,
'quantityOnhand': n.quantityRequested,
'updated': now,
'lastPickUp.date': now,
'lastPickUp.quantity': n.quantityRequested
}
}
};
var options = {upsert: true};
Companies.findOneAndUpdate(query1, update1, function (err, doc) {
if (!doc) {
Companies.findOneAndUpdate(query2, update2, function (err, doc) {
if (err) {
throw err;
}
});
}
});
//save smallparts
n._id = new ObjectId();
var smallPart = new SmallPart(n);
smallPart.order = order._id;
smallPart.quantity = n.quantityRequested;
smallPart.company = req.user.company;
smallPart.user = req.user;
smallPart.location = req.user.location;
smallPart.date = req.body.date;
order.smallParts.push(smallPart._id);
smallPart.save(function (err) {
// callback(null, order);
if (err) {
console.log(err);
}
});
})
}
callback(null, order)
}
],
function (err) {
if (!err) {
order.save(function (err) {
if (!err) {
res.status(200).json();
} else {
console.log('error saving order')
}
});
} else {
console.log(err);
}
});
};

MEAN: Getting total value from mongodb

Im new to mean stack and Im using mongoskin to connect to mongodb..Im trying to get total value present in database
function getTotal() {
var deferred = Q.defer();
var dashboard = db.collection('dashboard');
db.collection('dashboard').find({"iscorrect" : ""}).count(),
function (err, doc) {
if (err){
deferred.reject(err);
} else{
deferred.resolve();
}
};
return deferred.promise;
}
my main controller has
function gettotal(req, res) {
userService.getTotal()
.then(function () {
res.sendStatus(200);
})
.catch(function (err) {
res.status(400).send(err);
});
}
The following code does not return any value...Any help in getting total value is helpful
Because count() method is asynchronous and returns a promise, you can restructure your function as either using a callback function
function getTotal() {
var deferred = Q.defer();
db.collection('dashboard').count({"iscorrect" : ""}, function (err, result) {
if (err){
deferred.reject(err);
} else{
deferred.resolve(result);
}
});
return deferred.promise;
}
or since count() returns a Promise, just return it
function getTotal() {
// just return a Promise
return db.collection('dashboard').count({"iscorrect" : ""});
}
and in your controller:
function gettotal(req, res) {
userService.getTotal()
.then(function (count) {
res.status(200).json({ 'count': count });
})
.catch(function (err) {
res.status(400).send(err);
});
}