How I insert a data in MongoDB node.js? - node.js

Here my server side code
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
address: {
building: String,
coord: [Number],
street: String,
zipcode: String
},
borough: String,
cuisine: String,
grades: [{
date: Date,
grade: String,
score: Number
}],
name: String,
restaurant_id: String
});
module.exports = class RestaurantDB{
constructor(connectionString){
this.connectionString = connectionString;
this.Restaurant = null;
}
async addNewRestaurant(data){
let newRestaurant = new this.Restaurant(data);
await newRestaurant.save();
return `new restaurant: ${newRestaurant._id} successfully added`
}
I am new to MongoDB. So can you tell me how I add new data to my MongoDB atlas using "addNewRestaurant()" Node.js

you can just call addNewRestaurant with whatever data you want, matching your schema.
import RestaurantDB from "./RestaurantDB.js";
var rdb = new RestaurantDB('xxxxx'); // pass here the connection string
// then the data to write
await rdb.addNewRestaurant({
name: 'test'
})

Related

mongoose-schema - are both children array + parent doc's ID necessary?

I'm using a couple of one-to-many models and was wondering what the advantage of having both an array of "children" ObjectID()s and a "parent" model's ObjectID() in the child is. For example:
// a client will have a new card every ten visits
var ClientSchema = new Schema({
first_name: String,
last_name: String,
email: String,
cards: [] // ObjectID()s, <--- is this necessary?
});
var CardSchema = new Schema({
client: ObjectID(), // <--- or is this enough?
visits: []
});
I think the client: ObjectID() should do the trick in most cases, specially with the Population options Mongoose offers.
It suffices to store the reference ObjectId in one of the documents.
As you can read in the documentation or in this answer, the reference field needs a type and a ref. The name of field is arbitrary. Once you have done this and registered your models, you can use the models to populate your queries.
var clientSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
var cardSchema = new Schema({
client: {
type: Schema.Types.ObjectId,
ref: 'client'
}
});
// models
var Card = mongoose.model('Card', cardSchema);
var Client = mongoose.model('Client', clientSchema);
Yet, it could be helpful to store an array of ObjectId's. However, this also creates a huge window for mistakes. A mismatch of foreign key and primary key, in SQL dialect. You can always do a count query if you need to count. I would say, do either the above or do this:
var clientSchema = new Schema({
first_name: String,
last_name: String,
email: String,
cards: [
{
type: Schema.Types.ObjectId,
ref: 'card'
}
]
});
var cardSchema = new Schema({
card_name: String
});
// models
var Card = mongoose.model('Card', cardSchema);
var Client = mongoose.model('Client', clientSchema);

Mongoose : Error referencing sub schema

My user model
'use strict';
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var UserSchema = new mongoose.Schema({
id: String,
username: String,
firstName: String,
lastName: String,
initials: String,
password: String,
age: Number,
dateJoined: Date,
contactNo: String,
email: String,
about: String,
groupId: Number,
adminMode: Boolean,
simpulPoints: Number,
})
//Define model for user
const User = {
UserModel: mongoose.model("user", UserSchema),
}
module.exports = {
UserSchema : UserSchema,
User : User
}
My Events Model
'use strict';
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var UserSchema = require("../models/user").UserSchema
var EventSchema = new mongoose.Schema();
EventSchema.add({
id: String,
title: String,
description: String,
organizerId: String, //Simpul admin user responsible for event
startDate: Date, //MM-DD-YYYY HH:MM:SS:sssZ
endDate: Date,
group: String,
locaction: String,
googleMapsLink: String,
hasPassed: Boolean,
attendees: Number,
registeredUsers: [UserSchema],
groupId: Number,
adminMode: Boolean,
simpulAward: Number,
});
//Define model for evnt
var Event = {
EventModel : mongoose.model("event", EventSchema),
}
module.exports = {
Event : Event,
EventSchema : EventSchema
}
I'm getting the infamous "throw new TypeError('Invalid value for schema Array path" error with the 'registeredUsers' field. I've followed multiple posts with the same problem and can't seem to find where I am going wrong. According to my knowledge, I've exported the schemas appropriately. Any help/tips welcome
I ended up moving the Schema declarations out into a separate file and it seemed to do the trick. Suspect it must have been some file rights issue VSCode had with the users.js file

Generate test data from mongoose model

I have this model in nodejs app
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ServiceSchema = new Schema({
Taxy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Taxy',
required: 'Taxy cannot be blank'
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: 'User cannot be blank'
},
Servicio: String,
Minutos: Number,
Costo: Number,
Desc: String,
From: String,
To: String,
created: {
type: Date,
default: Date.now
}
});
mongoose.model('Service', ServiceSchema);
I have surfed for a couple of days and I have not found a framework to generate random data from a model service, something like
var Service = require('mongoose').model('Admin').schema;
var jsondata = generateRandomeFromModel(Service)
You can use mongoose-fakery module to generate test data
Example:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String,
surname: String
});
mongoose.model('User', UserSchema);
In your tests or fixture files:
var fakery = require('mongoose-fakery');
fakery.fake('user', mongoose.model('User'), {
name: 'john',
surname: 'doe'
});
You can go with complete reference here
You can use a package called Faker that makes it easier.
npm install #faker-js/faker --save-dev
get relational data by $sample (aggregation)
const { faker } = require('#faker-js/faker');
const mongoose = require('mongoose');
const getFakeData = async () => {
const taxy=await Model.Taxy.aggregate([{ $sample: { size: 1 } }]); //Randomly select document from `Taxy` Model
const user=await Model.User.aggregate([{ $sample: { size: 1 } }]);
return ({
Taxy: taxy.length && taxy[0]._id,
User: user.length && user[0]._id,
Servicio: faker.commerce.productAdjective(),
Minutos: faker.datatype.number(),
Costo: faker.datatype.number(),
Desc: String,
From: faker.name.findName(),
To: faker.name.findName(),
created: Date.now().toString()
});
}
const fakeJsonData = await getFakeData();
I found a working solution it was created 2 years ago. I tested it too it is working.
https://www.npmjs.com/package/mongoose-dummy

TypeError object is not a function

I'm developing an application in node.js with MongoDB
I have to files:
product.js and displaycost.js
this is product .js:
var mongoose = require('mongoose');
var Category = require('./category');
var productSchema = {
name:{type: String, require: true},
//Pictures mus start with "http://"
pictures:[{type:String, match: /^http:\/\//i}],
price:{
amount:{type: Number, required: true},
//ONly 3 supported currencies for now
currency:{
type: String,
enum:['USD','EUR','GBP'],
required: true
}
},
category: Category.categorySchema
};
var schema = new mongoose.Schema(productSchema);
var currencySymbols ={
'USD': '$',
'EUR':'€',
'GBP':'£'
};
/*
*
*/
schema.virtual('displayPrice').get(function(){
return currencySymbols[this.price.currency] +
'' + this.price.amount;
});
schema.set('toObject', {virtuals:true});
schema.set('toJSON', {virtuals:true});
module.exports = schema;
What I need is create a record with "productSchema"
I tried with this:
var Product = require('./product.js');
var p = new Product({
name: 'test',
price:{
amount : 5,
currency: 'USD'
},
category: {
name: 'test'
}
});
console.log(p.displayPrice); // "$5"
p.price.amount = 20;
console.log(p.displayPrice); //" $20"
//{... "displayPrice: "$20",...}
console.log(JSON.stringify(p));
var obj = p.toObject();
But when I run the displaycost.js throw me an error at the word "new"
and writes "TypeError: object is not a function"
I don't know why is happening that. Thank you.
you missing export mongoose model with model name.
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Category = require('./category');
var productSchema = new Schema({
name: {type: String, require: true},
pictures: [{type: String, match: /^http:\/\//i}],
price: {
amount: {type: Number, required: true},
currency: {
type: String,
enum: ['USD', 'EUR', 'GBP'],
required: true
}
},
category: Category
});
var currencySymbols = {
'USD': '$',
'EUR': '€',
'GBP': '£'
};
productSchema.virtual('displayPrice').get(function () {
return currencySymbols[this.price.currency] +
'' + this.price.amount;
});
productSchema.set('toObject', {virtuals: true});
productSchema.set('toJSON', {virtuals: true});
module.exports = mongoose.model('Product', productSchema);
"new" can only be called on a function. not an object.
In program.js you are creating a new instance of the mongoose schema.
var schema = new mongoose.Schema(productSchema);
... more code ...
return schema;
In your other js file you require product. At this point in time product.js has returned an object to you. A new mongoose schema. It is an object which you are refering to as Product.
You then try to create a new instance of it by calling new on the product OBJECT. New cannot be called on an object literal. It can only be called on a function.
I don't believe you need to make a new instance of schema within product.js, just return the function that creates the schema. Then call new on it when you require it like you are in your second file.

Mongoose object id is null

I'm creating an object Registration (a Mongoose Schema) and I need to set its Id in User with this line: registrationId: registration._id});
However, the Id is still null, even though it's the callback function? When I check the database the Registration has and Id of course, but not in the callback. How can I set the Id of the Registration in User?
Edit2: changed to minimal example. This prints out two times null.
exports.create = function(req, res) {
Registration.create(req.body, function(err, registration) {
if(err) { return handleError(res, err); }
console.log(registration._id);
console.log(registration.id);
return res.json(201, registration);
});
};
Edit: this is the schema (I left out some fields that are not required):
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var RegistrationSchema = new Schema({
isReservation: Boolean,
//Id of the trip
tripId: String,
//socialMutuality
codeGerechtige: String,
socialMutualityNumberParent1: String,
socialMutualityNumberParent2: String,
//contact
userId: String,
firstnameContact: String,
lastnameContact: String,
emailContact: String,
streetContact: String,
streetNumberContact: String,
zipcodeContact: String,
busContact: String,
cityContact: String,
phoneContact: String,
gsmContact: String,
socialSecurityNumberContact: String,
//coordinats of person that pays
//child information
//emergency contacts
emergencyContacts: [{
firstName: String,
lastName: String,
phone: String
}],
extraInfo: String
});
module.exports = mongoose.model('Registration', RegistrationSchema);
Problem and solution: the problem was the client sending an attribute _id = null, and that's why MongoDB/Mongoose didn't update the id.
removing _id from req.body fixed my issue.
if(req.body._id === null) {
delete req.body._id;
}
There must be something else going on in your code which is effecting this. This example works as expected for me:
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/createid');
var RegistrationSchema = new Schema({
isReservation: Boolean,
//Id of the trip
tripId: String,
//socialMutuality
codeGerechtige: String,
socialMutualityNumberParent1: String,
socialMutualityNumberParent2: String,
//contact
userId: String,
firstnameContact: String,
lastnameContact: String,
emailContact: String,
streetContact: String,
streetNumberContact: String,
zipcodeContact: String,
busContact: String,
cityContact: String,
phoneContact: String,
gsmContact: String,
socialSecurityNumberContact: String,
//coordinats of person that pays
//child information
//emergency contacts
emergencyContacts: [{
firstName: String,
lastName: String,
phone: String
}],
extraInfo: String
});
var Registration = mongoose.model('Registration', RegistrationSchema);
var reg = {
userId: '1234',
tripId: '2345',
firstnameContact: 'Timothy',
lastnameContact: 'Strimple',
emailContact: 'tim#tstrimple.com'
};
Registration.create(reg, function(err, registration) {
if(err) { throw err; }
console.log(registration._id);
});
I get a valid id written out to the console.

Resources