I have two tables
let SalesItemsSchema = new Schema({
name: {type: String, required: true},
quantity : {type:Number , required:true},
sale_id: {type: String, required: true},
amount : {type:Number , required:true},
purchase_amount : {type:Number , required:true},
} , {timestamps : true});
let InventorySchema = new Schema({
name: {type: String, required: true, max: 100},
quantity: {type: Number, required: true},
} , {timestamps:true});
I want to get the remaining items in the inventory. For example 100 items of something were added to the inventory and 90 of them were sold.
i want to get the difference from two tables (which will be 10)
i am using mongoose.
Related
I am using Mongoose and MongoDB v. 6.4.1. I have defined a document collection with embedded subdocuments using the following Mongoose schemas:
import mongoose, { Collection } from 'mongoose';
const connectStr = 'mongodb://localhost/appdb';
mongoose.set('useFindAndModify', false);
//Open connection to database
mongoose.connect(connectStr, {useNewUrlParser: true, useUnifiedTopology: true})
.then(
() => {console.log(`Connected to ${connectStr}.`)},
err => {console.error(`Error connecting to ${connectStr}: ${err}`)}
);
//Define schema that maps to a document in the Users collection in the appdb
//database.
const Schema = mongoose.Schema;
const roundSchema = new Schema({
date: {type: Date, required: true},
course: {type: String, required: true},
type: {type: String, required: true, enum: ['practice','tournament']},
holes: {type: Number, required: true, min: 1, max: 18},
strokes: {type: Number, required: true, min: 1, max: 300},
minutes: {type: Number, required: true, min: 1, max: 240},
seconds: {type: Number, required: true, min: 0, max: 60},
SGS: {type: Number,
default: function(){return (this.strokes * 60) + (this.minutes * 60) + this.seconds}
},
notes: {type: String, required: true}
});
const userSchema = new Schema({
id: {type: String, required: true}, //unique identifier for user
password: String, //unencrypted password (for now!)
displayName: {type: String, required: true}, //Name to be displayed within app
authStrategy: {type: String, required: true}, //strategy used to authenticate, e.g., github, local
profileImageUrl: {type: String, required: true}, //link to profile image
rounds: [roundSchema],
securityQuestion: {type: String},
securityAnswer: {type: String, required: function() {return this.securityQuestion ? true: false}}
});
//Convert schema to model
const User = mongoose.model("User",userSchema);
In an Express.js GET route, I am using the following code to query for a specific document:
try {
let thisUser = await User.findOne({id: req.params.userId});
console.log("thisUser: " + JSON.stringify(thisUser));
if (!thisUser) {
return res.status(400).send("No user account with specified userId was found in database.");
} else {
return res.status(200).json(thisUser.rounds);
}
} catch (err) {
console.log(err);
return res.status(400).message("Unexpected error occurred when looking up user in database: " + err);
}
My console.log statement confirms that the above route in fact obtains the desired document, e.g.:
thisUser: {"_id":"5e6704234f3864318caedd12","id":"chundhau#gmail.com","password":"GoCougs20","displayName":"chundhau#gmail.com","authStrategy":"local","profileImageUrl":"https://www.gravatar.com/avatar/4b565c54d37b3f5ad4caa1c129e865b8","securityQuestion":"First pet?","securityAnswer":"Daisy","__v":0,"rounds":[]}
When I look at this same document in MongoDB Compass Community, I can confirm that its rounds subdocument array has several elements:
However, as shown in the console.log output above, rounds is coming back as an empty array. I have confirmed that (a) rounds is in fact an array (using Array.isArray()) and that (b) rounds has no elements (thisUser.rounds.length === 0).
Shouldn't I be able to access all of the subdocuments through thisUser.rounds? What have I done wrong?
I have discovered a solution. I changed:
let thisUser = await User.findOne({id: req.params.userId});
to
let thisUser = await User.findOne({id: req.params.userId}).lean();
Miraculously, thisuser.rounds was no longer empty. It instead contained all of the array elements I could see when I inspected the document in MongoDB Compass Community!
While this solution worked, I do not know why it worked. If anyone could help me understand what's going on here, I'd appreciate it!
I have a db schema which requires linkedin url of the people signing up. I dont want them to fill the linkedin id on signup itself, they are free to add it at dashboard. Below given is the code for the model
const master = mongoose.model('master', new mongoose.Schema({
firstName: {type: String, required: true, unique: false},
lastName: {type: String, required: true, unique: false},
email: {type: String, required: true, unique: true },
linkedinUrl: {type: String, required: false, unique: false },
password: {type: String, required: true, unique: false}
},{strict: true}))
When I leave the field empty more than once, the db returns me an error
error: "{"driver":true,"name":"MongoError","index":0,"code":11000,"errmsg":"E11000 duplicate key error collection: maindb.mentors index: linkedinUrl_1 dup key: { : \"\" }"}"
I realise that having multiple null value is an issue. What other value can I use to mask the empty field? Thank you
I'm making a database for beavers, however some properties should be unchangeable such as the birth date or the location where it was first seen.
How do I implement this? Is there a mongoose schema property for this? Or do I do it with JS?
Example of the schema:
let beaverSchema = new Schema({
id: {type: String, required: true, unique: true},
birthDate: {type: Date},
locationSpotted: {type: String},
firstSeen: {type: Date},
status: {type: String, default: "Alive"},
sex: {type: String}
})
I have a simple app which lists tour guides and reviews left by users about each guide. Any user can give be a guide and can give reviews. My scheme for a user is:
var User = new mongoose.Schema({
firstName: { type: String, required: true, unique: true },
lastName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true}
isGuide: Boolean,
rating: {type: Number, "default": 0, min: 0, max: 5},
reviews: [reviewSchema]
});
var Review = new mongoose.Schema({
userId: {type: Schema.ObjectId, ref: 'User'},
author: {type: String, required: true},//contatenation of firstName and lastName of user that wrote review
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: {type: String, required: true},
createdOn: {type: Date, "default": Date.now}
});
mongoose.model('User', User);
I want to be able to:
1/ show a guide and all that guide's reviews
2/ show all a user's reviews
3/ show all guides a user has reviewed
I think my schema above is fine for 1. But is it suitable for 2 and 3? Am I understanding the MonboDB philosophy correctly?
I'm building a resume building app with Mongoose and Express. I set my models up so that education and work experience are both in their own collections. something similar to this:
"degree" : "BA",
"major" : "Econ",
"minor" : "Bus. Admin",
"startDate" : ISODate("2013-12-31T00:00:00Z"),
"endDate" : ISODate("2013-01-01T00:00:00Z"),
"user" : "example#gmail.com",
"created" : ISODate("2013-10-15T19:32:09.357Z"),
"_id" : ObjectId("525d9839ddc8bf7855000001"),
"school" : {
"name" : "university of alabama",
"loc" : "austin, tx"
},
"__v" : 0
I have a reference to the _id of the User model in the "user" value. my User model looks like so:
var schema = mongoose.Schema({
_id: {type: String, lowercase: true, trim: true, validate: validEmail }
, name: { first: String, last: String}
, salt: {type: String, required: true}
, hash: {type: String, required: true}
, edu: [{type: String, ref: 'Education'}] });
When I try to populate the edu section of my User model with information from the education model it's not finding anything.
My query is this:
var query = User.findById(user)
.populate('edu');
So how would I properly allow my User model make references to the education model so that I can send info from both to a view? Could I populate to fields like that?
Any advice would be mega helpful. I'll be scouring the docs, google and trying random things that kind of make sense in the mean time.
Thank you.
You need to use the mongoose.Schema.Types.ObjectId type in order for populate to work properly.
var schema = mongoose.Schema({
_id: {type: String, lowercase: true, trim: true, validate: validEmail }
, name: {first: String, last: String}
, salt: {type: String, required: true}
, hash: {type: String, required: true}
, edu: [{type: mongoose.Schema.Types.ObjectId, ref: 'Education'}] });
side note:
you don't need to define _id as you get that automatically and it should not be an email. Use a separate email field for that.