mongoose add more key:value inside ref field - javascript

organs: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Organ',
healthValue: { // i want to add this field but it is becoming invalid, not generating auto with default val
type: Number,
default: 0,
}
},
],
I have a user schema and also there is organs key in this schema. I'm keeping organs with ref way to get belongs to user organs. I also should keep organ health value but I can not keep it in ref field together as above. How can i do this? Can not I add more key:value to populate (type & ref) fields?

organs: [
{
organId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Organ',
},
healthValue: {
type: Number,
default: 0,
},
isOwned: {
type: Boolean,
default: false,
},
},
],
i think i solve with above code block, i did use wrong syntax

Related

How to ensure randomatic creates a unqiue identifier?

I'm using randomatic npm to store id to mongoDB as mongo only creates a long objectID which can not be used for invoice numbers. My current model is:
orders: [
{
orderReference: { type: String },
orderStatus: { type: String },
orderType: { type: String },
orderDate: { type: Date, default: Date.now },
itemDetails: { type: String },
purchaseOrder: {
orderReference: { type: String },
orderStatus: { type: String },
orderType: { type: String },
orderDate: { type: Date, default: Date.now },
itemDetails: { type: String },
},
thirdPartyOrder: {
orderReference: { type: String },
orderType: { type: String },
orderDate: { type: Date },
itemDetails: { type: String },
},
platformRevenue: {
orderReference: { type: String },
orderType: { type: String },
orderDate: { type: Date, default: Date.now },
itemDetails: { type: String }
}
}
],
In the current model how do I check/query that the ID that is currently in other orders are not duplicate and actually unique. Because randomatic doesn't create a unique ID by itself. It just creates a random ID whereas in my use case I want a unique 4 DIGIT NUMBERIC ID for orderReference.
Is there a possibility that four-digit random unique ids will finish one day and I should rather create sequential IDs instead which an increment of +1?
What is the industry standard of creating IDs for orderReferencing. I have mostly seen 4 to 6 digit number IDs on all the invoices I have received in my life.
Please help and suggest the best possible use-case.
I would rather use your second suggestion, sequential IDs with increments.
While it is possible to use randoms, you are likely to check if a specific ID is already in the database before inserting, in which case you have to generate new IDs.
What's more, with a sequential version you will be able to keep a (approximate) track on the invoice / number of invoice.
The limit will be 10.000 different IDs either way (including 0).
Hope it helps!

MongoDB Unique objectId in document [duplicate]

I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?
You call the index method on your Schema object to do that as shown here. For your case it would be something like:
mySchema.index({field1: 1, field2: 1}, {unique: true});
Defining indexes at the schema level is necessary when creating compound indexes.
animalSchema.index({ name: 1, type: -1 });
Reference: http://mongoosejs.com/docs/guide.html#indexes
import { Schema, Document, model } from 'mongoose';
import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';
export interface IUserMoodLocation extends Document {
userId?: IUser['_id'];
moodId?: IMood['_id'];
locationId?: ILocation['_id'];
}
const UserMoodLocationSchema: Schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
moodId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Mood'
},
locationId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Location'
}
});
UserMoodLocationSchema.index(
{ userId: 1, moodId: 1, locationId: 1 },
{ unique: true }
);
export const UserMoodLocation = model<IUserMoodLocation>(
'UserMoodLocation',
UserMoodLocationSchema
);
Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..
}
}
I have tested with sample data it is perfectly working as expected.
By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300 you should wrap the field names in single quotes, ie:
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
Happy Day!

Not able to add default values to the object in array

I am trying to add the fancyItem to the below model. Whenever I try to add the next fancyITem I get below mongo db error:
MongoError: E11000 duplicate key error collection: natours.fancyitems index: books.name_1 dup key: { : null }\n
To avoid this I am trying to add the default values to the objects so that I don't get this duplicate error.
Kindly suggest better way to handle this issue!
const mongoose = require("mongoose");
const fancyItemSchema = new mongoose.Schema({
firstName: {
type: String,
required: [true, "Please enter fancyItem's first name"]
},
lastName: {
type: String
},
genre: {
type: String,
enum: [
"guidingLights",
"luminaries",
"mavericScientists",
"menOfLetters",
"theGrandPhilosophers",
"architectsOfTheFuture"
],
required: true
},
notableWork: {
type: String,
required: [true, "Please enter notable work"]
},
quotes: [
{
quote: {
type: String,
default: "There is no quote"
}
}
],
books: [
{
bookName: {
type: String,
sparse: true,
default: "There is no quote"
},
bookURL: {
type: String,
sparse: true,
default: "There is no quote"
}
}
],
videos: [
{
videoName: {
type: String,
maxlength: [
50,
"A video description must have less or equal to 50 characters"
],
sparse: true,
default: "There is no quote"
},
videoURL: {
type: String,
sparse: true,
default: "There is no quote"
}
}
],
courses: [
{
courseName: {
type: String,
sparse: true,
default: "There is no quote"
},
courseURL: {
type: String,
sparse: true,
default: "There is no quote"
},
platform: {
type: String,
sparse: true,
default: "There is no quote"
}
}
]
});
const FancyItem = mongoose.model("FancyItem", fancyItemSchema);
module.exports = FancyItem;
Error you have provided says that there's already a record with null as the name. In other words, you already have a book without a name.
The relevant documentation for this:
If a document does not have a value for the indexed field in a unique
index, the index will store a null value for this document. Because of
the unique constraint, MongoDB will only permit one document that
lacks the indexed field. If there is more than one document without a
value for the indexed field or is missing the indexed field, the index
build will fail with a duplicate key error.
You can combine the unique constraint with the sparse index to filter
these null values from the unique index and avoid the error.
Unique Indexes
Sparse indexes only contain entries for documents that have the
indexed field, even if the index field contains a null value.
Sparse Indexes

Pushing object into array using MongoDB syntax and SimpleSchema validation

The idea is to push an object that looks like this into a field called likes, which is an array:
{
movieId: "VgtyvjVUAjf8ya",
information: {
genre: "Action",
length: "160",
language: "English"
}
}
I thought this would do it:
Meteor.users.update({_id: Meteor.userId()}, {$push: {likes: {movieId: movieId, information: informationObj}}})
But either it is wrong or the validation by SimpleSchema has some issues (it doesn't complain, though) because all I get is an empty object in an array! And no, there's nothing wrong with the values themselves, I have checked.
The SimpleSchema for the field in question looks like this:
likes: {
type: [Object],
optional: true
}
I've tried reading through the documentation but I don't really understand what's wrong. Anyone knows?
If you don't care to validate the objects that get pushed into the likes property, you can set blackbox to true in your schema, like so:
likes: {
type: [Object],
optional: true,
blackbox: true
}
This will allow you to put whatever you want into a "like" object.
If you do want to validate the "like" objects, then you'll need to create some additional schemas, like so:
var likeInfoSchema = new SimpleSchema({
genre: {
type: String
},
length: {
type: String
},
language: {
type: String
}
});
var likeSchema = new SimpleSchema({
movieId: {
type: String
},
information: {
type: likeInfoSchema
}
});
Meteor.users.attachSchema(new SimpleSchema({
// ...
likes: {
type: [likeSchema]
}
}));

Storing Javascript Array of Objects in Mongo DB using Mongoose

I have an array of the form [{key: ..., type: ..., value: ...}] and want to store it in the fields field in the following schema:
var articleSchema = mongoose.Schema({
name: {
type: String,
unique: true,
required: true
},
updated: {
type: Date,
default: Date.now
},
pageviews: {
type: Number,
default: 0
},
fields: [{
key: String,
type: String,
value: String
}],
image: String
});
I am doing this as follows, my Javascript array referenced as keyValueObj
Article.findOneAndUpdate(
{ name: articleName },
{
fields: keyValueObj
},
{ upsert: true },
callback
);
However, all that is stored in the database in the fields field is an array of strings like this: ["[object Object]"]
How can I store my Javascript array so that it matches my mongoose schema correctly?
I was able to fix this using Molda's idea of using a separate schema.
The updated fields field in the articleSchema now looks like this:
fields: [{
type: Schema.Types.ObjectId,
ref: 'Field'
}]
I then converted the array to an array of schema objects, like this:
keyValueObj = keyValueObj.map(function(fieldObj){
return new Field({
key: fieldObj.key,
type: fieldObj.type,
value: fieldObj.value
});
});
I was then able to store keyValueObj the was doing it in the initial code.

Categories

Resources