Mongoose schema + nodejs - node.js

I'm kinda new in mongodb and i'm in trouble
I can't reach a data from my mongo database
const mongoose = require('mongoose');
const Team = new mongoose.Schema({
name: String,
});
const MatchsSchema = new mongoose.Schema({
begin_at: Date,
number_of_games: Number,
name: String,
tournament: {
name: String,
},
opponents: {
type: [Team],
default: undefined
},
});
const Matchs = mongoose.model('matchs', MatchsSchema);
module.exports = Matchs;
I am trying to access with this code witch is return my "data" :
console.log(element.opponents[0]);
data returned
but when i want to access with .name the value is undefined
console.log(element.opponents[0].name);
database schema : db
I have an collection named "teams" in my db.
What is the problems ? I think i'm not that far...

It might be an overlook but try...
console.log(element.opponents[0].opponent.name);

db answer
My schema was not correct, with a modification that worked fine

Related

Mongoose populate returns empty array with a simple,non-nested population

I am trying to populate a model but I am getting a empty array in return. I went throught every stack overflow answer but nothing solved my issue.
Here's my main schema:
const companySchema = new Schema({
name:{type:String,required:true},
img:{data: Buffer,contentType: String},
users:[{
name:String,
email:String,
allottedWarehouse:String,
}],
brands:[{type:Schema.Types.ObjectId,ref:'Brand'}],
warehouses:{type:Array},
shops:{type:Array}
})
Here's how I am trying to populate
exports.getCompanyDetails = function(req,res){
Company.findById(req.params.id)
.populate('brands')
.exec(function(err,selectedCompany){
if(err){
res.json('Something went wrong!')
}
console.log(selectedCompany.brands)
res.json(selectedCompany);
})
}
But in database it's just empty brands array,no id reference at all.
When I return it in res.json,it's empty too.
Here's my simple brand schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BrandSchema = new Schema(
{
name: {type: String, required: true},
packSize:{type: Number, required: true},
})
module.exports = mongoose.model('Brand',BrandSchema);
I so badly need your help on this. Please look at it guys!Tell me where I am going wrong.

Error when using _id as a property type in a Mongoose Schema

I am learning MongoDB and mongoose at the moment. I have a Archive and a User schema in mongoose:
archive.js
var mongoose = require('mongoose');
var User = require('../users/user');
var notesSchema = new mongoose.Schema({
author: User.userId,
text: String,
files:[String]
});
var archiveSchema = new mongoose.Schema({
name: String,
priority: String,
deadline: Date,
status: String,
assigned_memnbers: [User.userId],
notes: [notesSchema],
});
archiveSchema.virtual('archiveId').get(function() {
return this._id;
});
module.exports = mongoose.model('Archive', archiveSchema);
user.js:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
username: String,
mail: String,
bio: String,
password: String
});
userSchema.virtual('userId').get(function() {
return this._id;
});
module.exports = mongoose.model('User', userSchema);
When I run my server i get the error
TypeError: Invalid value for schema path `author`, got value "undefined"
The the problem comes from author: User.userId, but I don't know how to make a reference between the two tables.
For reference, here is what my complete db design more or less looks like:
Any input on how to solve this problem or improve the overall design is welcome. Thanks you.
I think what you're talking about is a reference to other collection:
author: { type: Schema.Types.ObjectId, ref: 'User' }
and
assigned_members: [{ type: Schema.Types.ObjectId, ref: 'User' }]
should work fine.
Source: Mongoose population
I faced the same issue.I had imported a module, It was just not exporting from another module. so I have added:
exports.genreSchema = genreSchema;

Mongoose Find By Ref ID

so I have two schemas, User und Company
const UserSchema = new mongoose.Schema({
_createdAt: Date,
company: {type: mongoose.Schema.Types.ObjectId, ref: 'company'},
email: String,
});
const CompanySchema = new mongoose.Schema({
_createdAt: {
type: Date,
required: true
},
name: {
type: String,
required: true
}
});
const userModel = mongoose.model("user", UserSchema, "user");
const companyModel = mongoose.model("company", CompanySchema, "company");
I would now like to query for a specific User by his Company _id, but for some reason this is not working, it returns an empty array even though I have a user with the exact company ObjectId in my Database.
userModel.find({company: "5cfa4352ffc1c8135d8276a4"})
.exec((err, user) => {
console.log(user);
}
In my mongo shell the command
db.user.find({company: "5cfa4352ffc1c8135d8276a4"})
returns the users as expected so why does this not work in mongoose? Thanks in advance
Try this
const ObjectId = require('mongodb').ObjectID;
then
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
I hope it will work
If you want to find by that id you probably need to do this:
const mongojs = require('mongojs');
const ObjectId = mongojs.ObjectId;
db.user.find({company: ObjectId("5cfa4352ffc1c8135d8276a4")})
Since you are using moongose, you can get the ObjectId like this:
const mongoose = require('mongoose');
const objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa')

Nested Documents in Mongoose

I have two Mongoose schemas, User and Code. Each user can have many codes.
user.js:
var mongoose = require('mongoose');
var codeSchema = require('./code');
var userSchema = mongoose.Schema({
google: {
id: String,
token: String,
email: String,
name: String
},
codes: [codeSchema]
}, {collection : 'users'});
code.js:
var mongoose = require('mongoose');
var codeSchema = mongoose.Schema({
code: String,
name: String,
link: String
}, {collection: 'codes'});
module.exports = codeSchema;
My problem is, whenever I access a user's array of codes by user.codes, I get something like { _id: 56c4c82a37273dc2b756a0ce },{ _id: 56c4c82a37273dc2b756a0cd } rather than the JSON for a code.
What am I missing?
You're missing populate.
By default, Mongoose will only give you the _ids of any references made in a document. populate allows you to fill out nested documents.
userSchema.findOne({}).populate('codes');
More here
please check that you are inserting other values or not this can be a case . Please write how you are inserting in array . I have two other way check out
There are two way to do this
1-->either you save refrence id of codeschema and
2--> is you can insert whole codeschema in array
1. codes: {
type: mongooseSchema.ObjectId,
ref: 'codeSchema',
required: true
},
and when all data is in array 56c4c82a37273dc2b756a0ce,56c4c82a37273dc2b756a0cd
that can be done by this query
domain.User.update({_id:id}
,{$addToSet:{code:codeObjvalue}},
function(err,res){});
and then populate them by this
domain.users.find({},'code')
.populate('code','code color email').
exec(function(err,results){
callback(err, results);
});
2-- and second is to insert whole code schema in userschema
create a codeschema object and add in set like this
var codeobj={};
codeobj.code="xyz";
codeobj.email="xyz#gmail.com"
var codeobject = new domain.code(codeobj);
domain.User.update({_id:id},{$addToSet:{code:codeobject}},function(err,user1){
});
Woops, turns out I was using the wrong dataset, not adding the codes properly (facepalm). Thanks to everyone who answered!

Saving Mongoose object into two collections

Currently I have a node application which uses mongoose to save an object into a MongoDB. I am using a model similar to this:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var RegistrationSchema = new Schema({
name:{ type: String, default: '', trim: false}
});
mongoose.model('Registration', RegistrationSchema);
Which saves my objects into a collection called registrations.
I save my registrations as such:
var registration = new Registration(data);
registration.save(function(err) {
if (err) {
return callback({
source: 'data_save',
type: 'admin',
errors: err
});
}
else {
return callback(null, data);
}
});
I would also like to save this same object when I create it, into another collection with a different name, such as registrations_new, or something to that effect. I want to duplicate this entry into the new collection. I tried to add the other collection in the connection string, which broke the mongo part entirely, I tried to create a new model called New_Registration, load that Schema and try to save it individually, but I have another issue with that. It seems that Mongoose pairs the schema with the collection, and that there really is no way to overwrite which collection it is saving to.
Anyone have any solution for this?
You can use the same schema in multiple models, so something like this works:
var RegistrationSchema = new Schema({
name:{ type: String, default: '', trim: false}
});
var Registration = mongoose.model('Registration', RegistrationSchema);
var New_Registration = mongoose.model('New_Registration', RegistrationSchema);
var registration = new Registration(data);
registration.save();
var new_registration = new New_Registration(data);
new_registration.save();

Resources