Mongoose, Select a specific field with find - javascript

I'm trying to select only a specific field with
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
But in my json response i'm receiving also the _id, my document schema only has two fiels, _id and name
[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]
Why???

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Or explicitly via an object:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};

There is a shorter way of doing this now:
exports.someValue = function(req, res, next) {
//query with mongoose
dbSchemas.SomeValue.find({}, 'name', function(err, someValue){
if(err) return next(err);
res.send(someValue);
});
//this eliminates the .select() and .exec() methods
};
In case you want most of the Schema fields and want to omit only a few, you can prefix the field name with a - (minus sign). For ex "-name" in the second argument will not include name field in the doc whereas the example given here will have only the name field in the returned docs.

There's a better way to handle it using Native MongoDB code in Mongoose.
exports.getUsers = function(req, res, next) {
var usersProjection = {
__v: false,
_id: false
};
User.find({}, usersProjection, function (err, users) {
if (err) return next(err);
res.json(users);
});
}
http://docs.mongodb.org/manual/reference/method/db.collection.find/
Note:
var usersProjection
The list of objects listed here will not be returned / printed.

Tip: 0 means ignore & 1 means show.
Example 1:
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
Example 2:
User.findById(id).select("_id, isActive").then(...)
Example 3:
User.findById(id).select({ _id: 1, isActive: 1, name: 1, createdAt: 0 }).then(...)

DB Data
[
{
"_id": "70001",
"name": "peter"
},
{
"_id": "70002",
"name": "john"
},
{
"_id": "70003",
"name": "joseph"
}
]
Query
db.collection.find({},
{
"_id": 0,
"name": 1
}).exec((Result)=>{
console.log(Result);
})
Output:
[
{
"name": "peter"
},
{
"name": "john"
},
{
"name": "joseph"
}
]
Working sample playground
link

Exclude
Below code will retrieve all fields other than password within each document:
const users = await UserModel.find({}, {
password: 0
});
console.log(users);
Output
[
{
"_id": "5dd3fb12b40da214026e0658",
"email": "example#example.com"
}
]
Include
Below code will only retrieve email field within each document:
const users = await UserModel.find({}, {
email: 1
});
console.log(users);
Output
[
{
"email": "example#example.com"
}
]

The precise way to do this is it to use .project() cursor method with the new mongodb and nodejs driver.
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })

I found a really good option in mongoose that uses distinct returns array all of a specific field in document.
User.find({}).distinct('email').then((err, emails) => { // do something })

Related

How do I add new field in existing JSON

I have JSON with 10000 unique records and I need to add another field with a unique value to every record. How do I add that?
[
{
_id: "5fffd08e62575323d40fca6f",
wardName: "CIC",
region: "ABC",
location: "AAA",
specialism: "CSR",
__v: 0
},
.
.
.
]
The JSON is stored in variable showWard. How do I add an action field in my JSON with value = './wardName' where wardName is already a field in my JSON?
This is my current code:
app.get('/wards', function (req, res) {
Ward.find({}, function (err, showWard) {
if (err) { console.log(err); return; }
return res.send(showWard);
});
});
Using a .map()? I don't know the logic for determinate the gender, but in Ward.find() callback you can add a thing like that:
app.get('/wards', function (req, res) {
Ward.find({}, function (err, showWard) {
if (err) { console.log(err); return; }
const newShowWard = showWard.map(ward => {
ward.gender = "BOH";
return ward;
})
return res.send(newShowWard);
});
});

Mongoose update function is giving null and not actually updating information

My .findOneAndUpdate method is returning user as null and isn't ending up updating the information. Everything seems to be in order, I'm not getting any erros.
EDIT: I have made progress, I was able to finally update the GroupID, but its setting it as null. Instead of the passed in string.
router.put("/update", (req, res) => {
Users.findOneAndUpdate(
{ _id: req.body.id },
{
$set: { GroupID: req.body.GroupID }
},
{ new: true },
(err, user) => {
if (err) res.send(err);
else res.send("Account GroupID Updated" + user);
}
);
});
You have to convert req.body.id to objectId as follows:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(req.body.id);
Users.findOneAndUpdate(
{ _id: id }

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

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.

Cannot read property 'push' of undefined

Here's my mongoose schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CartSchema = new Schema({
userID: String,
items: [{
itemID: String,
quantity: Number
}]
});
module.exports = mongoose.model('Cart', CartSchema);
Here's the node.js server which uses Express. It has /add-to-cart route which if triggered it should update user's cart with the information passed in req.body:
router.post('/add-to-cart', function(req, res, next) {
Cart.find({ userID: req.body.userID }).then(function(userCart){
console.log("TEST: "+JSON.stringify(userCart));
var myItem = {itemID: req.body.itemId, quantity: 1}
userCart.items.push(myItem);
res.send(userCart);
}).catch(next);
});
I printed to terminal userCart as you can see in my code and it returned me this:
[{
"_id":"58f7368b42987d4a46314421", // cart id
"userID":"58f7368a42987d4a46314420", // userid
"__v":0,
"items":[]
}]
When the server executes userCart.items.push(myItem); it returns this error:
Cannot read property 'push' of undefined
Why items is not defined if I've already defined its structure in mongoose?
As adeneo correctly pointed out, userCart is clearly an array but you need to use one of the update methods to push the document to the items array, would suggest Model.findOneAndUpdate() as in
router.post('/add-to-cart', function(req, res, next) {
Cart.findOneAndUpdate(
{ userID: req.body.userID },
{ $push: { items: { itemID: req.body.itemId, quantity: 1 } } },
{ new: true }
)
.exec()
.then(function(userCart) {
console.log("TEST: "+ JSON.stringify(userCart));
res.send(userCart);
})
.catch(next);
});
As adeneo pointed out userCart is an array since you are you are using the find method. But clearly you need to find just one document given by its userID so it advised to use findOne() instead.
Also you will need to save the document in order for the changes to actually reflect.
Have a look at the updated code below:
router.post('/add-to-cart', function(req, res, next) {
Cart.findOne({ userId: req.body.userID }, function(err, userCart){
if(err) return next(err);
console.log("TEST: "+JSON.stringify(userCart));
var myItem = {itemID: req.body.itemId, quantity: 1}
userCart.items.push(myItem);
userCart.save(function(err, usersCart) {
if(err) return next(err);
res.send(usersCart);
})
})
});
Hope this helped.
This can be solved using:
router.post('/add-to-cart', function(req, res, next) {
Cart.findOne({ userID: req.body.userID }).then(function(userCart){
console.log("TEST: "+JSON.stringify(userCart));
const a = req.body.items;
for(i=0;i<a.length;i++)
{
userCart.items.push(req.body.items[i]);
}
res.send(userCart);
}).catch(next);
});

Categories

Resources