mongoose model to connect to mongoDB - mongodb

i have created model for the mongo collection like below. but it was giving me the collection output which saved in mongoDB.
var mongoose = require('mongoose'),
Schema = mongoose.Schema({
name: {
type: String
},
age: {
type: Number
},
})
module.exports = mongoose.model('container', Schema);}
But later when i changed the last line of the code which is
"module.exports = mongoose.model('container', Schema);"
to
"module.exports = mongoose.model('container', Schema, 'container');"
it worked properly. I check the mongoose document they say to use the previous line, then why didn't it worked.

your problem seems to be from using "Schema" as a variable name
var ContainerSchema = new mongoose.Schema({
...
});
and exporting
module.exports = mongoose.model("Container", ContainerSchema);
would work.

Related

Mongodb collection name changed after creation

Problem is that then I run this code, after I check the db records with Robomongo on windows, I see only one collection created with name 'maximas' with two records,
if I remove Model2 from code, after creation result will be the same, but must be collection 'maxima'.
Is there bug in code that i don't see, or this word is reserved, any ideas?
The code,
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mymodels', (e)=>{
if(e) throw e;
});
var schema = new mongoose.Schema({
text: {type: String}
});
var Model1 = mongoose.model('maxima', schema);
var Model2 = mongoose.model('maximas', schema);
var newData1 = new Model1({
text: 'test'
});
var newData2 = new Model2({
text: 'test'
});
newData1.save((e)=>{
if(e) throw e;
console.log('Saved');
});
newData2.save((e)=>{
if(e) throw e;
console.log('Saved');
});
Mongoose will automatically pluralise your model name as the collection name. This is why they are both the same, as the second collection name is already in plural form.
You can pass the desired collection name as the third model argument:
var Model1 = mongoose.model('maxima', schema, 'maxima');
var Model2 = mongoose.model('maximas', schema, 'maximas');
NOTE: You can also specify your collection name as an option in your schema:
var schema = new mongoose.Schema({
text: { type: String }
}, {
collection: 'maxima'
});
...but in this case you would require a second schema so the first approach above is more suitable here.

building a schema mongodb

Whilst building the following schema
'use strict';
var User = mongoose.model('checkIn')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var checkIn = new Schema({
email: {
type: String
// default:User.local.email
},
checkInDate: {
type:Date,
default:Date.now()
}
})
module.exports = mongoose.model('User', checkIn);
I encountered the following error message
How do I fix this?
The error clearly says, "cannot read property of undefined". That means "mongoose" is undefined when it reaches var User = mongoose.model('checkIn'). Of course, because the require statement var mongoose = require('mongoose'); comes afterwards. You should put the require statement first so that 'mongoose' is available when you call model property on it.

Subdocument based on another document

I was wondering if it's possible in Mongoose to have a subdocument based on another document.
Normally I would do something like this:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var CountrySchema = new Schema({
name: String,
info: String,
cities : [
{
type: Schema.ObjectId,
ref: 'Ressource'
}
]
});
module.exports = mongoose.model('Country', CountrySchema);
this however create a new document and then references it via the id to the country document. This is not what I want, I want the resource document to be nested inside the country document. How would I do this?
I found that this fixed my problem:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ressourceSchema = require('../ressource/ressource.model');
var CountrySchema = new Schema({
name: String,
info: String,
cities : [
ressourceSchema.schema
]
});
module.exports = mongoose.model('Country', CountrySchema);

mongo mongoose populate subdocument returns null

I am trying to use node & mongoose's populate method to kind of 'join' 2 collections on query. The following is my schema setup:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ShopSchema = new Schema({
ssss: { type: Schema.Types.ObjectId, required :true, ref: 'Stat' },
ratings: [RatingSchema]
});
var RatingSchema = new Schema({
stat: { type: Schema.Types.ObjectId, required :true, ref: 'Stat' }
}, {_id: false});
Also I have setup the Stat mongoose model so that the queries works without error (but the result is not what I expected).
I tried to perform the following queries:
ShopSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('ssss', '_id stat_id').exec(cb);
};
mongoose.model('Shop', ShopSchema);
This gives me the correct result and the ssss is correctly referenced.
The result is something like this .
"ssss":{"_id":"5406839ad5c5d9c5d47091f0","stat_id":1}
However, the following query gives me the wrong result.
ShopSchema.statics.load = function(id, cb) {
this.findOne({
_id: id
}).populate('ratings.stat', '_id stat_id').exec(cb);
};
mongoose.model('Shop', ShopSchema);
This gives me ratings.stat = null for all results. Could someone tell me what I did wrong? Thanks.
I just found the answer by trial and error.....
in the last example ShopSchema is declared before the RatingSchema. So I am guessing Mongoose doesn't know exactly what is happening inside RatingSchema and making the populate returns an error. So if you declare RatingSchema before the ShopSchema and the populate method is working like a charm..

Mongoose/MongoDB - Saving a record to overwrite current data:

So I have a object in the DB that is basically blog posts, there is a array of ObjectID's in there that reference the Categories collection.
So
Posts = {
title: String,
Content: String,
Categories: [{
type: ObjectID,
ref: 'Categories'
}]
I can create the posts fine, problem comes when I try to update them:
post.title = 'hi';
post.content = 'content';
post.categories = ['44523452525','4e1342413421342'];
post.save(function(){});
For some reason it will ADD those 2 categories instead of wiping the categories array and inserting those.
How do I get it to remove those and insert new ones?
I tried to reproduce this behavior but I couldn't - here's the code sample I ran:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
mongoose.connect('mongodb://localhost/testjs');
PostSchema = new Schema({
title:String,
content:String,
cats:[]
});
var Post = mongoose.model('Post', PostSchema);
var mypost = new Post()
mypost.title = "x"
mypost.content = "y"
mypost.cats = ['a','b','c']
mypost.save(
function(err){
mypost.cats = ['d','e']
mypost.save()
}
);
After the second call to save() the array contains only what it was set to ("d","e"). Can you try it and see if you get the same result? Maybe it's related to mongoose version, or something.