This is Morning Star schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var morningStarSchema = new Schema({
title : {type: String, lowercase : true, required :true},
visit : {type: String, lowercase : true, required :true},
Sightseeing : {type: String, lowercase : true, required :true},
image : {type: String},
price : {type: String},
})
module.exports = mongoose.model('morningStar',morningStarSchema)
API for Morning Star schema
created database in MongoDB with collections lets cruise and snow vacations with data in it , but when I do get request I get an empty array
var morningStar = require('../models/morningstar')
module.exports = function (router) {
router.post('/lets-cruise', function(req, res) {
var user = new morningStar();
user.title = req.body.title;
user.visit = req.body.visit;
user.Sightseeing = req.body.Sightseeing;
user.image = req.body.image;
user.price = req.body.price
user.save();
res.send('User created')
});
router.get('/snow-vacations', function(req, res){
morningStar.find(function(err, company) {
if (err)
{
res.send(err);
} else {
res.json(company);
}// return all nerds in JSON format
});
});
return router;
}
Related
Tried to insert auto increment number for serial number in mongodb using mongoose and nodejs but not working.Where i want to update my code to find solution.If anyone knows please help to find solution.
subs.model.js:
const mongoose = require('mongoose');
var subscriberSchema = new mongoose.Schema({
_id: {type: String, required: true},
email: {
type: String
}
}, {
versionKey: false,
collection: 'subscribers'
});
module.exports = mongoose.model('Subscribers', subscriberSchema);
data.controller.js:
module.exports.subscribeMail = (req, res, next) => {
var subscribeModel = mongoose.model("Subscribers");
var subscribemailid = req.query.email;
var subscribe = new subscribeModel({
email: subscribemailid
});
var entitySchema = mongoose.Schema({
testvalue: { type: String }
});
subscribe.save(function(error, docs) {
if (error) { console.log(error); } else {
console.log("subscribe mail id inserted");
console.log(docs)
res.json({ data: docs, success: true });
}
});
entitySchema.pre('save', function(next) {
var doc = this;
subscribe.findByIdAndUpdate({ _id: 'entityId' }, { $inc: { seq: 1 } }, function(error, counter) {
if (error)
return next(error);
doc.testvalue = counter.seq;
next();
});
});
};
If i use above code inserting data into mongodb like below:
_id:5f148f9264c33e389827e1fc
email:"test#gmail.com"
_id:6f148f9264c33e389827e1kc
email:"admin#gmail.com"
But i want to insert like this
_id:5f148f9264c33e389827e1fc
serialnumber:1
email:"test#gmail.com"
_id:6f148f9264c33e389827e1kc
serialnumber:2
email:"admin#gmail.com"
You can use this plugin: https://www.npmjs.com/package/mongoose-auto-increment
First you need to initialize it after creating Mongoose connection:
const connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
Than in your subs.model.js file:
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
var subscriberSchema = new mongoose.Schema({
_id: {type: String, required: true},
email: {
type: String
}
}, {
versionKey: false,
collection: 'subscribers'
});
subscriberSchema.plugin(autoIncrement.plugin, {
model: 'Subscribers',
field: 'serialnumber'
});
module.exports = mongoose.model('Subscribers', subscriberSchema);
I have 3 schemas
1. User
2. SignedToEvent
3. Events
The User contains information about user and has a relation to SignedToEvents. The SignedToEvents couples the user to an event.
The SignedToEvent is nested within User like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SignedToEvents = new Schema({
event : { type: Schema.Types.ObjectId, ref: 'event' },
eventSignedDate: {type : Date, default : Date.now()},
isActive : Boolean
})
SignedToEvents.set('toObject', { getters: true });
SignedToEvents.set('toJSON', { getters: true });
const UserSchema = new Schema({
email: String,
password : String,
age : Number,
sex : String,
createdAt: { type: Date, default: Date.now },
signedToEvents : [SignedToEvents]
})
UserSchema.set('toObject', { getters: true });
UserSchema.set('toJSON', { getters: true });
module.exports = mongoose.model('user', UserSchema, 'users');
And the event schema looks like this
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventSchema = new Schema({
shortId : String,
name: String,
description : String,
organization : String
})
module.exports = mongoose.model('event', eventSchema, 'events');
In my API I have a call to the User collection:
User.findOne({_id : mongoose.Types.ObjectId(req.userId)})
.select("email")
.populate("event")
.exec()
.then(docs=>{
console.log(docs)
res.status(200).send(docs.signedToEvents)
});
Now, my hopes was to get an aggregated collection of User, SignedToEvent and Event. However thats not the case.
It only returns users id and email.
/Thanks
The solution was to point to my signedToEvent property and then use .event to reach the event model. Like this:
User.findOne({_id : mongoose.Types.ObjectId(req.userId)})
.select("email")
.populate("signedToEvents.event")
.exec()
.then(docs=>{
console.log(docs)
res.status(200).send(docs.signedToEvents)
});
I am using mongoose module
I have two Schema file
//First User File
var mongoose = require('mongoose');
const UserActivitySchema = require('./useractivity')
//User Schema
var UserSchema = new mongoose.Schema({
username: {
type: String
},
activity: [UserActivitySchema]
});
var User = module.exports = mongoose.model('User', UserSchema, 'User');
I already Tried to Create a subdocument but not able to acheive it
//Second Schema i.e supposed to be child is on useractivity.js file
var mongoose = require('mongoose');
//User Activity Schema....011217
var UserActivitySchema = mongoose.Schema({
message_count:{
type: Number,
default: 0
}
});
exports.UserActivitySchema = UserActivitySchema;
By this, It will create the Entry like this:
{
"_id" : ObjectId("5ab38941ffbb87124c673862"),
"username" : "peter",
"activity" : []
}
What I want is to like this:
{
"_id" : ObjectId("5ab38941ffbb87124c673862"),
"username" : "peter",
"activity" : {
"message_count" : 0
}
}
Any help is really Appreciated..
Mongoose populate can help you to get the required functionalities. You can learn more about populate here. You can do it in this way,
Create UserActivitySchema
var mongoose = require('mongoose');
var UserActivitySchema = mongoose.Schema({
message_count:{
type: Number,
default: 0
}
});
module.exports = mongoose.model('UserActivity', UserActivitySchema, 'UserActivity');
Now create UserSchema like this
var mongoose = require('mongoose');
const UserActivitySchema = require('./useractivity')
//User Schema
var UserSchema = new mongoose.Schema({
username: {
type: String
},
activity: {
type: mongoose.Schema.Types.ObjectId,
ref: 'UserActivity',
}
});
var User = module.exports = mongoose.model('User', UserSchema, 'User');
Now, while you are saving a user save the _id of the UserActivity in activity
When you are making your query to get user you can do like this
User.findOne({_id: 5ab38941ffbb87124c673862})
.populate('UserActivity')
.exec(function(err, user) {
// do stuff with returned user
});
I have two mongoose schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var itemSchema = new Schema({
name: {type: String, required: true, max: 25, trim: true},
price: {type: Number, required: true, trim: true, default: 0},
tax: {
type: Schema.Types.ObjectId,
ref: "Store"
}
});
module.exports = mongoose.model('Item', itemSchema);
The second Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var storeSchema = new Schema({
name: {type: String, required: true, trim: true},
taxes: [
{
name: String,
rate: Number
}
]
});
module.exports = mongoose.model('Store', storeSchema);
What I want to do is populate the itemSchema tax object with the storeSchema taxes array of object. every time I pushed a new tax object to the taxes array mongoose created an ObjectId. I stored that ObjectId in my itemSchema Tax. I want to use that _id to retrieve the store taxes that matches the itemSchema _id.
I have tried this so far, but I get no in the tax attribute.
Item.find().populate("tax", "taxes").exec(function (err, docs) {
if (err) return console.error(err);
console.log(items);
});
Try this query
Item.find().populate({
path: 'tax',
select: 'taxes'
}).exec(function (err, docs) {
if (err) {
console.error(err);
} else {
console.log(docs);
}
});
Item.find().populate(path:"tax", model: )
Mention your item model file name... don't use "" or '' for the file name, simply add the file name.
Use Item.find().populate("Store", "taxes") instead of Item.find().populate("tax", "taxes").
Essentially I am just trying to add a new sub-document to my existing mongodb document that has the following schema
/models/server/destination.js
// this is the "destination" model for mongoose
var mongoose = require('mongoose')
var Adventure = require('../models/adventure')
// this is the schema that every entry will get when a new trip is made.
var tripSchema = mongoose.Schema({
name: { type: String, required: true },
city: { type: String, required: true },
dateStart: { type: Date, required: true },
dateFinish: { type: Date, required: true },
adventures: [Adventure]
})
// module.exports makes this model available to other file
module.exports = mongoose.model('Destination', tripSchema)
/server/models/adventure.js
var mongoose = require('mongoose')
var adventure = mongoose.Schema({
site: String,
rating: String,
photo: String,
website: String,
date: Date
})
module.exports = mongoose.model('Adventure', adventure)
REST route to post to adventures
app.post('/api/destinations/:id/addAdventures', destinationsController.addAdventures)
/server/controllers/controller.js
module.exports.addAdventures = function(req, res) {
var id = req.params.id;
Destination.findOne({ _id: id }, function(err, result) {
var adventure = new Adventure(req.body)
var destination = result
destination.adventures.push(adventure)
destination.save(function(err, advresult) {
console.log('push worked')
res.json(advresult);
})
})
}
When I take the adventure out of the destination.adventures.push() the code does not break, but when I insert adventures I get an error
/Travellog/node_modules/mongoose/lib/types/array.js:117
return this._schema.caster.cast(value, this._parent, false);
^ TypeError: undefined is not a function
at Array.MongooseArray.mixin._cast (/Travellog/node_modules/mongoose/lib/types/array.js:117:32)
at Array.MongooseArray.mixin._mapCast (/Travellog/node_modules/mongoose/lib/types/array.js:286:17)
at Object.map (native)
at Array.MongooseArray.mixin.push (/Travellog/node_modules/mongoose/lib/types/array.js:299:25)
at Query.<anonymous> (/Travellog/server/controllers/destinations-controller.js:28:28)
at /Travellog/node_modules/mongoose/node_modules/kareem/index.js:177:19
at /Travellog/node_modules/mongoose/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:355:11)
The error you are getting is as a result of embedding the Adventure model instead of the schema. You need to add the Adventure schema in the destination schema definition the Adventure model's schema property:
// this is the "destination" model for mongoose
var mongoose = require('mongoose');
var AdventureSchema = require('../models/adventure').schema; /* <- access the schema via its Model.schema property */
var tripSchema = mongoose.Schema({
name: { type: String, required: true },
city: { type: String, required: true },
dateStart: { type: Date, required: true },
dateFinish: { type: Date, required: true },
adventures: [AdventureSchema]
});