Mongoose distinct returns empty array - mongodb

I have the following schema and query. I'm trying to retrieve all tags in my document by using the .distinct() method but that's not working. Any suggestions would be great.
const postingSchema = new mongoose.Schema({
time: String,
date: String,
company: String,
position: String,
description: String,
tags: Array,
});
router.get('/tags', async function(req, res){
const tags = await Postings.find({}).distinct("tags").exec();
if(!tags){
return res.status(404).json({message: "No Tags!"});
}
return res.status(200).json(tags);
}

Related

Is there a way to convert a date value to a User's timezone in Mongoose?

I have searched everywhere, StackOverflow and else where but I can't seem to find a fix for my problem. I have a mongoose schema like this:
// user.model.js
const mongoose = require('mongoose');
const User = new Schema({
firstName: String,
lastName: String,
tz: String,
registrationDate: {
type: Date,
default: Date.now(),
}
})
And I have a controller which creates a User like this:
// user.controller.js (async)
let user = await User.create({
'firstName': 'John',
'lastName': 'Doe',
'tz': 'Africa/Kampala'
});
await reply.send(user); // I am using Fastify framework
No matter what I do, when the User is returned it always gives the UTC time and not the time that the User actually is in. have tried using Mongoose transform:
// Transform on the schema
const moment = require('moment-timezone');
const User = new Schema({
// Schema definitions
}, {
toJSON: {
transform: function (doc, ret) {
ret.registrationDate= moment.tz(doc.registrationDate, doc.tz).format();
return ret;
}
}
})
And have also tried using get like this:
const User = new Schema({
// Other definitions
registrationDate: {
type: Date,
default: Date.now(),
get: convertDate
}
})
function convertDate(registrationDate) {
return moment.tz(registrationDate, this.tz).format()
}
But no luck. I would appreciate any assistance or guidance in getting this to work on the model. Thanks!

Unable to query sub document mongoose

I've schema like this and i', trying to get the document from the array using _id. This is my first Mongo project that I'm working, please help me how can I achieve the. I basically want to retrieve the sub document corresponds to the id and update some data in that.
var PhoneSchema = new mongoose.Schema({
type: String,
number: String
});
var StudentSchema = new mongoose.Schema({
name: String,
dept: String,
phone: [PhoneSchema]
});
var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);
I've tried the following ways, but none of them are working.
Method 1: When I tried the same in the console it is giving me the parent document along with the sub document that corresponds to the phoneId
Student.findOne({"phone._id":new mongoose.Schema.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err, student) {
}
Method 2: As per the mongoose documentation to retrieve sub documents, in this case I'm getting exception saying phone is undefined
Student.phone.Id(phoneId);
I've fixed this by removing Schema from the below query
Student.findOne({"phone._id":new mongoose.Types.ObjectId(phoneId) }, {'phone.$':1}, function(err, student) {
}
i tried to solve your requirement. The following code did the job.
var PhoneSchema = new mongoose.Schema({
type: String,
number: String
});
var StudentSchema = new mongoose.Schema({
name: String,
dept: String,
phone: [PhoneSchema]
});
var Phone = mongoose.model('Phone',PhoneSchema);
var Student = mongoose.model('Student',StudentSchema);
var newPhone = new Phone({
type: 'ios', number: '9030204942'
});
var newStudent = new Student({
name:'Pankaj',
dept:'cse',
phone:newPhone
});
// newStudent.save(function(err, ph) {
// if (err) return console.error(err);
// });
Student.findOne({"phone._id":mongoose.Types.ObjectId('587e6409e06170ba1708dc21') },{_id:0,phone:1}, function(err, phone) {
if(err){
console.log(err)
}
console.log(phone);
});
Find the following screenshot with result

Mongoose - pushing refs - cannot read property "push" of undefined

I would like to add a category and then if successed, push it's ref to user' collection. That's how I'm doing this:
That's mine "dashboard.js" file which contains categories schema.
var users = require('./users');
var category = mongoose.model('categories', new mongoose.Schema({
_id: String,
name: String,
ownerId: { type: String, ref: 'users' }
}));
router.post('/settings/addCategory', function(req, res, next) {
console.log(req.body);
var category_toAdd = new category();
category_toAdd._id = mongoose.Types.ObjectId();
category_toAdd.name = req.body.categoryName;
category_toAdd.ownerId = req.body.ownerId;
category.findOne({
name: req.body.categoryName,
ownerId: req.body.ownerId
}, function(error, result) {
if(error) console.log(error);
else {
if(result === null) {
category_toAdd.save(function(error) {
if(error) console.log(error);
else {
console.log("Added category: " + category_toAdd);
<<<<<<<<<<<<<<<<<<<THE CONSOLE LOG WORKS GOOD
users.categories.push(category_toAdd);
}
});
}
}
});
Here is my "users.js" file which contains "users" schema.
var categories = require('./dashboard');
var user = mongoose.model('users', new mongoose.Schema({
_id: String,
login: String,
password: String,
email: String,
categories: [{ type: String, ref: 'categories' }]
}));
So, the category add proccess works well and I can find the category in database. The problem is when I'm trying to push the category to user.
This line:
users.categories.push(category_toAdd);
I get this error:
Cannot read property "push" of undefined.
I need to admit once more that before that pushing there is console.log where the category is printed properly.
Thanks for your time.
The users object is a Mongoose model and not an instance of it. You need the correct instance of the users model to add the category to.
dashboard.js
...
category_toAdd = {
_id: mongoose.Types.ObjectId(),
name: req.body.categoryName,
ownerId: req.body.ownerId
};
// Create the category here. `category` is the saved category.
category.create(category_toAdd, function (err, category) {
if (err) console.log(err);
// Find the `user` that owns the category.
users.findOne(category.ownerId, function (err, user) {
if (err) console.log(err);
// Add the category to the user's `categories` array.
user.categories.push(category);
});
});

MongoDB Saving Sub Document

I m newbie mongo and node.js.I m using MongoDB and I working on Todo list app.
https://github.com/ishuah91/Nodejs-MongoDb-TodoMVC
This is my todo model
function init(Schema, mongoose){
var TheSchema = new Schema({
title: String,
complete: Boolean
});
return mongoose.model('Todos', TheSchema);
}
module.exports.init = init;
But I want to do this model will be saved as in other document like sub-documemt.
var mainDoc = Schema({
name:String,
author: String,
receiver: String,
list: [TheSchema]
});
You would have to do the following :
var mainDoc = Schema({
name:String,
author: String,
receiver: String,
list: {
title: String,
complete: Boolean
}
});

Storing values that aren't defined in the schema (dynamic schema?)

Suppose I have a Schema definition
var Users = mongoose.model('Users', new mongoose.Schema({
username: String,
salt: String,
hash: String,
facebook: {
id: String
}
}));
But I want to later
user = new Users({
username: 'myusername',
facebook: {
id: '3141592653',
displayName: 'mydisplayname' // <- wasn't in the schema ^
}
});
Then displayName simply doesn't gets stored. Is this not allowed in mongoose? Because I would imagine since MongoDB is "schema-less" there ought to be a way to do this?
You can disable the strict option on the schema to allow fields not in the schema to be saved:
var Users = mongoose.model('Users', new mongoose.Schema({
username: String,
salt: String,
hash: String,
facebook: {
id: String
}
}, { strict: false }));