retrieve date failed in mongoose - node.js

I defined my mongoose schema like this
var personSchema = new Schema({
id: 1
data: [{
dob: Date,
gender: String,
}]
});
Then I do
Person.find({"data.dob": new Date('1-2-2016')}, function(err,result) {
res.json(result)
});
I got empty array, any clue why? I also tried
Person.find({"data.dob": "1-2-2016"}, function(err,result) {
res.json(result)
});

Related

Inserting an object into a list on a mongoDB collection

I have a collection created with the below schema
const userSchema = new mongoose.Schema({
Name: String,
email: String,
music: Array
});
var User = new mongoose.model("User", userSchema);
However, i am having issue inserting the object below into the music array
var newMusic = {
artist: "Rihanna",
title: "Believe It"
};
Below is the code i am running to insert the above into the music array
User.update({
_id: req.user._id
}, {
$push: {
music: newMusic
}
});
No error message, just not updating the document.
I finally figured it out. The below code works
User.update({
_id: req.user._id
}, {
$push: {
music: newMusic
}
}).then(data => {
console.log(data);
});

How to populate data from nested object in mongoose

I am having schema like below:
const commentSchema = new Schema({
name: String,
surname: String,
email: String,
positions: [
{ detail: [{
type: Schema.Types.ObjectId,
ref: 'Position'
}],
progress: { type: String }, // keep track of the status
comment: { type: String } // keep track of internal notes
}],
});
Field detail contains array of mongo ids.
I am trying with below code but not getting the populated data:
const requirementsData = await Requirement.find({})
.populate({
path: "positions.detail",
model: Position,
})
.exec(function(err, docs) {
if(err){
console.log("err====", err)
}else{
res.render('candidates/show', {candidate: docs})
}
});
if I understand your problem you can do this
.populate({
path:'position',
populate:{path:'details'}
})

Populate in Mongoose not working

I am trying to perform associations by referencing method. There are 2 models:
1. User
2. Product
I have established one-to-one relationship of 1 user can have multiple products. User creation is successful
Product creation is successful
Code Inputs
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/product_demo_x9");
Product Schema
var productSchema = new mongoose.Schema({
category : String,
Brand: String
});
var Product = mongoose.model("product", productSchema);
User Schema
var userSchema = new mongoose.Schema({
email: String,
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product"
}
]
});`
var User = mongoose.model("user", userSchema);
User Creation
User.create({
email: "madhur#google.com",
name: "Maddy"
},function(err,newUser){
if(err){
console.log(err);
}
else {
console.log(newUser);
}
});
Product Creation
Product.create({
category: "Smartwatches",
Brand: "Samsung and Google"
},
function(err,product){
console.log(product);
User.findOne({name : "Maddy"},function(err,foundUser){
if(err) {
console.log(err);
}
else {
foundUser.products.push(product);
foundUser.save(function(err,updatedUser){
if(err){
console.log(err);
}
else {
console.log(updatedUser);
}
});
}
});
});
Display of associated Data on the console
User.find({email: "madhur#google.com"}).
populate("products").
exec(function(err,user){
if(err){
console.log(err);
}
else {
console.log(user);
}
});
Code Outputs
User Creation (Success)
[{
products: [],
_id: 5a47acb0317d4e3c2081b8ce,
email: 'madhur#google.com',
name: 'Maddy',
__v: 0
}]
Product Creation and associating (Success)
{
_id: 5a47acd53c771123b4018ff1,
category: 'Smartwatches_2',
Brand: 'Samsung and Google',
__v: 0
}
{
products: [ 5a47acd53c771123b4018ff1 ],
_id: 5a47acb0317d4e3c2081b8ce,
email: 'madhur#google.com',
name: 'Maddy',
__v: 1
}
Display of embedded data using populate - Failure!!
{ MissingSchemaError: Schema hasn't been registered for model "products".
Use mongoose.model(name, schema)
at new MissingSchemaError
Can anyone please explain me how to do it correctly?
Thanks in Advance
Model Name is Case-sensitive
'Product' is not equal to 'product'
and when u create a model as 'product' (singular) it converts it into plural, i.e. 'products', this is default mongoose behavior, can be overridden.
so change the following:
var userSchema = new mongoose.Schema({
email: String,
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "products" //<---- changed 'Product' to 'products'
}
]
});`
var User = mongoose.model("user", userSchema);
Try this
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/product_demo_x9');
var productSchema = new mongoose.Schema({
category: String,
Brand: String
});
var Product = mongoose.model('Product', productSchema);
var userSchema = new mongoose.Schema({
email: String,
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
]
});
var User = mongoose.model('User', userSchema);
User.create({
email: 'madhur#google.com',
name: 'Maddy'
}, function(err, newUser) {
if (err) {
console.log(err);
} else {
console.log(newUser);
}
});
Product.create({
category: 'Smartwatches',
Brand: 'Samsung and Google'
},
function(err, product) {
console.log(product);
User.findOne({name: 'Maddy'}, function(err, foundUser) {
if (err) {
console.log(err);
} else {
foundUser.products.push(product);
foundUser.save(function(err, updatedUser) {
if (err) {
console.log(err);
} else {
console.log(updatedUser);
}
});
}
});
});
User.find({email: 'madhur#google.com'})
.populate('products')
.exec(function(err, user) {
if (err) {
console.log(err);
} else {
console.log(user);
}
});
Solved
Did the following
Downgraded my Mongoose version from 5.00x to 4.10.8 using the following command npm remove mongoose then npm install mongoose#4.10.8 --save
Made the following change in app.js file
var userSchema = new mongoose.Schema({
email: String,
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "product" //<---- changed 'Product' to 'product'
}
]
});`
var User = mongoose.model("user", userSchema);
Thanks to the Stack community for giving a try!

Mongoose doesn't save nested Object in another nested Object

Usually in mongoose save the object nested, through the father's call method save, but if we have two levels of engagement, grandfather, father [nested], son [nested], the son is not saved through the father's call method save.
Grandfather -> Group
var schema = new mongoose.Schema({
name: String,
days:[mongoose.Schema.Types.Day],
});
module.exports = mongoose.model('Group', schema);
Father -> Day
var schema = new mongoose.Schema({
_id: Number,
matches:[mongoose.Schema.Types.Match]
});
module.exports = mongoose.model('Day', schema);
Son -> Match
var schema = new mongoose.Schema({
team1: {
type: Schema.ObjectId,
ref:'Team'
},
team2: {
type: Schema.ObjectId,
ref: 'Team'
},
score: [Number]
});
module.exports = mongoose.model('Match', schema);
In the routes ("matches.js") I try to save the group jointly day and match.
Group.findById(groupId).exec(
function(err, group){
var match = new Match();
var day = group.days[dayNumber-1];
day.matches.push(
match
);
group.save(function(err){
console.log("success");
console.log("group in matches.js:"+group);
res.redirect("/tournaments/"+tournamentId+"/groups/"+groupId+"/days/"+dayNumber);
});
});
In the redirect I print again the "group" and the match disappears.
app.get('/tournaments/:tournamentId/groups/:groupId/days/:dayNumber', function (req, res) {
groupId = req.params.groupId;
dayNumber = req.params.dayNumber;
Group.findById(groupId, function (err, group) {
console.log("group in days.js:"+group);
res.render('days/show', {
title: 'Days',
group: group,
day:group.days[dayNumber-1],
tournamentId: req.params.tournamentId
});
});
});
The console log print:
new match
success
group in matches.js:{ __v: 7,
_id: 53a3ee54dfe793bd9a20c6ab,
name: 'gruppo sdirubbo',
days: [ { matches: [Object], _id: 1 } ] }
GET /tournaments/539f0185ea17e46e73be937b/groups/53a3ee54dfe793bd9a20c6ab/days/1/newMatch 302 4ms - 208b
group in days.js:{ __v: 7,
_id: 53a3ee54dfe793bd9a20c6ab,
name: 'gruppo sdirubbo',
days: [ { matches: [], _id: 1 } ] }
mongoose.Schema.Types.Day and mongoose.Schema.Types.Match are undefined so those array fields that reference them are ending up as Mixed types instead which don't save unless you explicitly mark them modified.
You need to make those schemas available between the model definitions and then use those in your definitions instead. For example:
var matchSchema = new mongoose.Schema({
team1: {
type: Schema.ObjectId,
ref:'Team'
},
team2: {
type: Schema.ObjectId,
ref: 'Team'
},
score: [Number]
});
var daySchema = new mongoose.Schema({
_id: Number,
matches:[matchSchema]
});
var groupSchema = new mongoose.Schema({
name: String,
days:[daySchema],
});

Mongoose select with populate not working

I am making a query in mogoose and if i add any parameter on a query select, the populate parameter goes missing for example i have the following schemas:
Department:
var mongoose = require('mongoose');
var schema = mongoose.Schema({
name: {type:String,required: true,index: {unique: true}} ,
text: String
})
module.exports=mongoose.model('Department',schema);
Employee:
var mongoose = require('mongoose');
var ObjectId=mongoose.Schema.ObjectId;
var schema = mongoose.Schema({
name: {type:String,required: true} ,
lastName: {type:String} ,
birthday:Date,
email:{type:String,required: true,index: {unique: true}},
_department:{type:ObjectId,ref:'Department'},
isUser:Boolean
},{ strict:false});
module.exports=mongoose.model('Employee',schema);
if i make:
var query=mongoose.model('Employee').find();
query.select('email').populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
I get the following ouput
[ { email: 'email#email.com.br', _id: 532e570864803bf505e51c81 } ]
I would expect this:
[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
email: 'email#email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]
If i make the following:
var query=mongoose.model('Employee').find();
query.populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
I get this output
[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
name: 'mimimi',
email: 'email#email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]
What makes me wonder that the select is breaking the populate.
My mongoose version is 3.8.8
Surely you just specify the fields you want. Currently you only have "email" so that is all you get:
var query=mongoose.model('Employee').find();
query.select('email _department').populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
Try my code:
const Employee= require('../models/employee');
Employee.find({}, 'email _department')
.populate('_department', ['name'])
.exec(function(err, list_employee) {
if (err) { return next(err); }
//Successful
console.log(list_employee);
});
Will work for you!
Work for me this in mongoose and here company_name field is getting populate via reference
ModelName.find().populate('parent_id', 'company_name')
.select('username mobile firstname lastname company_name');

Resources