Receiving an error saying nested schema in MongoDB - mongodb

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
created: new Date()
})
const user = mongoose.model('user', userSchema);
module.exports = user;
After adding new Date() I get an error saying :
TypeError: Undefined type undefined at created
Did you try nesting Schemas? You can only nest using refs or arrays.

You are defining schema and you just need a type there not the object. Instead of using new Date() just use Date.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
created: Date
})
const user = mongoose.model('user', userSchema);
module.exports = user;

I would guess that your intention was to have a Date field type with a mongoose default value of the current date time ... since you named that field created. I would go a step further and name it created_At ...
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
created_At: { type: Date, default: Date.now }
})
const user = mongoose.model('user', userSchema);
module.exports = user;
Now you will have an auto filled created_At Date field every time you create a new user model.
We specifically said what type we want the field to be and we also added a default value.
You can read more about mongoose defaults here

Related

Mongoose adding url slug to the returned JSON object

Sorry in advance if my formatting is off! I'm building a project using MongoDB, Mongoose, and Express. Right now I'm trying to use Mongoose to read a document from the MongoDB database. For some reason it's prepending the word "slug" to the document I'm fetching from the database.
The result I'm getting is this:
[{"slug":"","title":"test","id":"62002ba44b05edb74c1a9cd8"}]
When the result I should be getting is this: [{"title":"test","id":"62002ba44b05edb74c1a9cd8"}]
I'm thinking there's an unexpected side effect from one of the libraries I'm using but I can't figure out what's causing it. It's like this before I call res.render("Test", testRes) so it might even be coming from the database like this somehow? I've been stumped on this for hours now.
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Test = mongoose.model('Test');
const sanitize = require('mongo-sanitize');
router.get('/test/:testSlug', async function(req, res) {
const testSlug = req.params.testSlug;
const testSearchParam = {
slug: sanitize(testSlug)
};
console.log("search param", testSearchParam.slug);
const testRes = await Test.find(
{
title: testSearchParam.slug
}
);
res.render("Test", testRes);
});
module.exports = router;
and here is my schema for the Test data format:
const mongoose = require('mongoose');
const URLSlugs = require('mongoose-url-slugs');
const { toJSON } = require('../plugins');
const TestSchema = new mongoose.Schema({
title: {
type: String,
required: true
}},
{
collection: 'test'
}
);
TestSchema.plugin(URLSlugs('title'));
TestSchema.plugin(toJSON);
/**
* #typedef Test
*/
const Test = mongoose.model('Test', TestSchema);
module.exports = Test;
Since you are using mongoose-url-slugs, the package has a default option to create a slug field in mongoose schema.
addField (Default: True) - Add slug field to mongoose schema.
See here: https://www.npmjs.com/package/mongoose-url-slugs#options-and-defaults

Mongoose - populate multiple ids

I am new to mongoose and I was strugling whole day trying to understand populate. I managed to do simple examples but now I created two schemas:
First which is UserSchema with some user details:
const UserSchema: mongoose.Schema = new mongoose.Schema ({
name: String,
email: String
});
And second which is MatchSchema witch I want to be populated with user details but I am not sure if something like this will work:
const MatchSchema: mongoose.Schema = new mongoose.Schema ({
player_one: {
id: String,
score: Number,
player_details: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},
player_two: {
id: String,
score: Number,
player_details: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},
winner: String
},{timestamps: true});
Probably I used something which wont work and any help will be appriciated.
You need to create a Mongoose model using the UserSchema and name it 'User'. You can then create a Match model using the MatchSchema. Assuming the UserSchema and MatchSchema are in the same file, you can add the following:
const User = mongoose.model('User', UserSchema)
const Match = mongoose.model('Match', MatchSchema)
Then when you want to populate the Match model with User data:
let data = Match.find({})
.populate('player_one.player_details')
.populate('player_two.player_details')

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.

Mongo Reference Schema Collections

I’m looking to confirm that my collection structures will correctly allow for the reference I’m trying to make between my collections. Ideally I have a parent collection labeled category, where the child collection is labeled images. I plan on having around 4 documents for my “category” collection and 30 documents for my “images”. All of the documents were going to be uploaded from the command line with a csv file format. If I set up my schemas like I do below and upload the documents with headers matching the fields in the schemas, will I not have an issue with the reference points?
Category
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = new Schema({
name: String,
description: String
});
var Category = mongoose.model(‘Category’, categorySchema);
module.exports = Category;
Images
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imageUrl: String,
category_id: { type: sechema.ObjectId, ref:"categorySchema"}
});
var Images = mongoose.model('Images', imageSchema);
module.exports = Images;
Here is the layout of my .csv files
category.csv
**name** **description**
Drama Stories about...
images.csv
**imageUrl** **category_id**
www.site.com/image.jpg Drama
Hopefully there can be only one category belonging to an image. One category having many images and each image belongs to only one category.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = new Schema({
name: String,
description: String
images: [{type: mongoose.Schema.Types.ObjectId, ref: 'Images'}]
});
var Category = mongoose.model(‘Category’, categorySchema);
module.exports = Category;
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imageUrl: String,
category_id: {type: mongoose.Schema.Types.ObjectId, ref:"Category"}
});
var Images = mongoose.model('Images', imageSchema);
module.exports = Images;
Note: You would reference your model not Schema.
Then on you can use mongoose middleware to update your references while saving.
imageSchema.pre('save', function(next){
var Category = require("../models/Category");
var image = this;
Category.findOneAndUpdate(
{_id: {$in: {this.category_id}},
{$push: {images: this._id}},
next
);
});

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);