I am working with mongoose schema and trying to get a parent obj in child from the child itself (I know it is not allowed in Javascript, but there are workarounds). This was my first implementation
const customer = mongoose.Schema({
name: String,
products_sold: [
{
name: String,
price: Number,
qty: Number,
},
{
name: String,
price: Number,
qty: Number,
},
],
messages: [
{
timestamp: {
type : Date,
default: Date.now
},
_my_key_: {
type: String,
default: () => {
// here i need to get products_sold.name in array like [products_sold[0].name, products_sold[1].name]
// this.products_sold does not work
},
},
}
]
})
I looked up some resources like this one. So i also tried
const customer = mongoose.Schema({
name: String,
products_sold: [
{
name: String,
price: Number,
qty: Number,
},
{
name: String,
price: Number,
qty: Number,
},
],
messages: [
{
timestamp: {
type : Date,
default: Date.now
},
_my_key_: {
type: String,
default: () => {
// here this.parent.products_sold does not work also
},
},
}
],
init: function(){
this.messages._my_key_.parent = this;
delete this.init;
return this;
}
}.init()
)
For Reference:
Mongoose Default Functions and This
This question does not answer mine.
EDIT # 1
I tried this with both arrow and regular function.
EDIT # 2
As per comment feedback from #Molda. After the above code, This is how i make the instance and save a record.
const Customer = mongoose.model('Customer', customer);
const customer = {
name: "John Doe",
products_sold: [
{
name: "product_name",
price: 1245,
qty: 2,
}
],
messages: [
{
// message timestamp will generate from default and _my_key_ too will generate from default
}
]
}
const callingFunc = async () => {
const cust = await Customer(customer);
await cust.save();
return cust;
};
Related
I have two model one is productModel.js and another is reviewModel.js. I did child referencing in reviewSchema. product Schema has ratingsAverage and ratingsQuantity property. I want to manipulate these properties of properties inside from reviewModel.js. So that I have used statics method on reviewSchema.
reviewModel.js:
const Product = require("./productModel");
const { Schema } = require("mongoose");
const mongoose = require("mongoose");
const reviewSchema = new Schema({
review: {
type: String,
},
rating: {
type: Number,
min: 1,
max: 5,
},
createdAt: {
type: Date,
default: Date.now(),
},
product: {
type: mongoose.Schema.ObjectId,
ref: "Product",
required: [true, "A review must belong to a tour."],
},
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: [true, "A review must belong to a user"],
},
});
// Preventing from duplication of review on same tour from same user
// Combined index
reviewSchema.index({ product: 1, user: 1 }, { unique: true });
// Creating calcAverageRating() static method for calculating average rating and number of ratings on product. It should work on creating, updating and deleting of review.
reviewSchema.statics.calcAverageRating = async function (productId) {
// "this" represents here model
const stats = await this.aggregate([
{
$match: { product: productId },
},
{
$group: {
_id: "$product",
nRating: { $sum: 1 },
avgRating: { $avg: "$rating" },
},
},
]);
console.log(stats, "rrrr");
// console.log(Product, "product");
// Problem is coming here i am not able to access productModel
// const doc = await Product.findByIdAndUpdate(
// productId,
// {
// ratingsAverage: stats[0],
// ratingsQuantity: stats[0],
// },
// {
// new: true,
// runValidators: true,
// }
// );
};
// As you know static methods only call on Model so we have to think about how to call calcAverageRating() static method. problem is that we have to get this product id which one is used to creating review so we only get this id on document middleware("post") for creating and for updating and deleting we will get from get from query middleware(/^findOne/).
// Document middleware("save")
reviewSchema.post("save", function () {
this.constructor.calcAverageRating(this.product);
});
reviewSchema.post(/^findOneAnd/, async function () {
// console.log(await this.findOne());
this.r = await this.clone().findOne();
console.log(this.r, "query");
console.log(Product, "testing");
});
reviewSchema.post(/^findOneAnd/, function () {
this.r.constructor.calcAverageRating(this.r.product);
});
// reviewSchema.pre(/^find/, function (next) {
// this.populate({
// path: "product",
// select: "name",
// });
// next();
// });
// CREATING MODEL
const Review = mongoose.model("Review", reviewSchema);
// We can call here static method but we will not get productId so we have to call this static method before creating of Model.
// Review.calcAverageRating();
// EXPORTING
module.exports = Review;
productModel.js:
const mongoose = require("mongoose");
const { Schema } = require("mongoose");
const Review = require("./reviewModel");
// CREATING SCHEMA
const productSchema = new Schema(
{
name: {
type: String,
required: [true, "Please enter product name"],
unique: true,
trim: true,
},
slug: String,
price: {
type: Number,
required: [true, "A product must have a price"],
maxlength: [8, "Price cannot exceeds 8 characters"],
},
priceDiscount: {
type: Number,
validate: {
validator: function (val) {
// this only points to current doc on NEW document creation
return val < this.price;
},
message: "Discount price ({VALUE}) should be below regular price",
},
},
stock: {
type: Number,
required: [true, "Please Enter product Stock"],
maxLength: [4, "Stock cannot exceed 4 characters"],
default: 1,
},
summary: {
type: String,
required: [true, "A product must have a summary"],
},
description: {
type: String,
required: [true, "A product have a description"],
},
images: [
{
public_id: {
type: String,
required: [true, "Images public id is required"],
},
url: {
type: String,
required: [true, "Images url is required"],
},
},
],
ratingsAverage: {
type: Number,
default: 0,
},
numOfReviews: {
type: Number,
default: 0,
},
reviews: [
{
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: true,
},
name: {
type: String,
required: true,
},
rating: {
type: Number,
required: true,
},
comment: {
type: String,
required: true,
},
},
],
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: true,
},
category: {
type: String,
required: [true, "A product must belong to a category"],
},
createdAt: {
type: Date,
default: Date.now(),
},
// ratingsAverage: {
// type: Number,
// default: 4.5,
// min: [1, "Rating must be above 1.0"],
// max: [5, "Rating must be below 5.0"],
// // Declaring custom function for do some opeartion from get value
// // set: (val) => Math.round(val * 10) / 10, // 4.666666, 46.6666, 47, 4.7
// set: (val) => Math.round(val * 10) / 10,
// },
// ratingsQuantity: {
// type: Number,
// default: 0,
// },
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
productSchema.index({ name: "text", description: "text" });
// VIRTUAL POPULATE
productSchema.virtual("reviews", {
ref: "Review",
foreignField: "product",
localField: "_id",
});
// CREATING MODEL
const Product = mongoose.model("Product", productSchema);
// EXPORTING
module.exports = Product;
I am trying to insert my nested object to Realm with To-One Relationships method, but I got an unexpected result where all value of my nested object is the same thing as the value from the first of my nested object that has been Relationship
This is my schema looks like
const PhotoSchema = {
name: 'CUSTOMER_PHOTOS',
properties: {
base64: 'string'
}
};
const TimeSchema = {
name: 'CUSTOMER_TIMES',
properties: {
warranty: 'float',
finish: 'float'
}
};
const MainSchema = {
name: 'CUSTOMERS',
primaryKey: 'id',
properties: {
id: 'int',
name: 'string',
photo: {type: 'CUSTOMER_PHOTOS'},
time: {type: 'CUSTOMER_TIMES'},
}
};
And try to insert some data like this
import Realm from 'realm';
Realm.open({
path: 'mydb.realm',
schema: [PhotoSchema, TimeSchema, MainSchema]
})
.then((realm) => {
realm.write(() => {
realm.create('CUSTOMERS', {
id: Date.now(),
name: 'John',
photo: {
base64: 'ImageBase64'
},
time: {
warranty: 31,
finish: 7
}
})
})
})
.catch((error) => {
console.error(error)
});
The process of inserting data is successfully BUT I got unexpected result when successfully get that data from Realm
Unexpected Result in console.log()
{
id: 1601335000882,
name: "John",
photo: {
base64: "ImageBase64"
},
// This value is the same as PhotoSchema
time: {
base64: "ImageBase64"
}
}
I want to the actual result like this
{
id: 1601335000882,
name: "John",
photo: {
base64: "ImageBase64"
},
time: {
warranty: 21
finish: 7
}
}
I there anything wrong with my code? The Documentation is not too detail about the method, the explanation and the example is just like one word
UPDATE:
I got an unexpected result only in the console.log() and if I try to access the property directly like MY_DATA.time.warranty the result is what I expected
The Answer is: No
To-One Relationships method is not only for one Schema, and Thanks to Angular San for showing an example of Inverse Relationships method.
Try Inverse Relationships
I got an expected result with Inverse Relationships method. In this method, you have to add one property that connected to Main Schema and I want to call this a combiner property
const PhotoSchema = {
name: 'CUSTOMER_PHOTOS',
properties: {
base64: 'string',
combiner: {type: 'linkingObjects', objectType: 'CUSTOMERS', property: 'photo'}
}
};
const TimeSchema = {
name: 'CUSTOMER_TIMES',
properties: {
warranty: 'float',
finish: 'float',
combiner: {type: 'linkingObjects', objectType: 'CUSTOMERS', property: 'time'}
}
};
const MainSchema = {
name: 'CUSTOMERS',
primaryKey: 'id',
properties: {
id: 'int',
name: 'string',
photo: 'CUSTOMER_PHOTOS',
time: 'CUSTOMER_TIMES',
}
};
I am trying to populate an array of id's from another collection
My JsonSchema looks like this:
{
version: 0,
type: "object",
properties: {
id: {
type: "string",
primary: true
},
// This is populated as expected
working: {
type: "array",
ref: "othercollection",
items: {
type: "string"
}
},
// This is where I am having problems
notWorking: {
type: "array",
items: {
type: "object",
properties: {
// This property is not being populated
problem: {
type: "array",
ref: "yetanothercollection",
items: {
type: "string"
}
}
}
}
}
}
}
From the docs at https://pubkey.github.io/rxdb/population.html I should be able to:
Example with nested reference
const myCollection = await myDatabase.collection({
name: 'human',
schema: {
version: 0,
type: 'object',
properties: {
name: {
type: 'string'
},
family: {
type: 'object',
properties: {
mother: {
type: 'string',
ref: 'human'
}
}
}
}
}
});
const mother = await myDocument.family.mother_;
console.dir(mother); //> RxDocument
Example with array
const myCollection = await myDatabase.collection({
name: 'human',
schema: {
version: 0,
type: 'object',
properties: {
name: {
type: 'string'
},
friends: {
type: 'array',
ref: 'human',
items: {
type: 'string'
}
}
}
}
});
//[insert other humans here]
await myCollection.insert({
name: 'Alice',
friends: [
'Bob',
'Carol',
'Dave'
]
});
const doc = await humansCollection.findOne('Alice').exec();
const friends = await myDocument.friends_;
console.dir(friends); //> Array.<RxDocument>
So my question is why can I not access myDocument.notWorking[0].problem_?
Here is a screenshot of the console that might give you a better understanding of my situation:
As you can see the ingredients property is not populated with the data from the ingredients collection (not in picture). The taxes property, however, is populated.
This is not possible unless you use OEM methods.
https://rxdb.info/orm.html
const heroes = await myDatabase.collection({
name: 'heroes',
schema: mySchema,
methods: {
whoAmI: function(otherId){
// Return the item with id `otherId` from the other collection here
return 'I am ' + this.name + '!!';
}
}
});
await heroes.insert({
name: 'Skeletor'
});
const doc = await heroes.findOne().exec();
console.log(doc.whoAmI());
I have a User model and a Book model. I want some data from my books to be denormalized on each User document, but still have the option to populate if needed. If I set ref: 'Book' on the books.$._id it gets populated inside the _id path which is unintended. I would like the population to overwrite the denormalized data.
How do I accomplish this?
in users.model.js:
const { Schema } = require('mongoose');
const UserSchema = new Schema({
name: String,
books: {
type: [
{
_id: Schema.Types.ObjectId,
title: String,
length: Number,
},
],
default: [],
},
});
Desired outcome
in users.controller.js:
app.get('/', async (req, res, next) => {
const users = await User.find({})
/*
users: [{
_id: ObjectId(),
name: 'Andrew',
books: [{
_id: ObjectId(),
title: 'Game of Thrones',
length: 298,
}, { ... }],
}, { ... }]
*/
});
app.get('/:id', async (req, res, next) => {
const book_id = req.params.id;
const user = await User.findById(book_id).populate({
path: 'books',
model: 'Book',
});
/*
user: {
_id: ObjectId(),
name: 'Andrew',
books: [{
_id: ObjectId(),
name: 'Game of Thrones',
length: 298,
author: 'Simone Dunow',
releasedOn: Date(),
price: 30,
...
}, { ... }],
}
*/
});
Schemas I've tried so far:
books: {
type: [
{
_id: Schema.Types.ObjectId,
title: String,
length: Number,
},
],
default: [],
ref: 'Book',
},
returns array of { _id: null }
books: {
type: [
{
_id: {
type: Schema.Types.ObjectId,
ref: 'Book',
},
title: String,
length: Number,
},
],
default: [],
},
books are populated inside of _id: { _id: { Book } }
books: {
type: [
{
type: {
_id: Schema.Types.ObjectId,
title: String,
length: Number,
},
ref: 'Book',
},
],
default: [],
},
throws exception: invalid type
const UserSchema = new Schema({
name: String,
books: [{
id: { type : Schema.Types.ObjectId, ref : 'Book'} //Whatever string you have used while modeling your schema
title: String,
length: Number,
}],
});
While using the schema you can populate as follows :
populate({ path: 'books.id' })
Output :
{
_id : // someid
name : "somename"
books : [
{
id : {//document referring to Books collection},
title : "sometitle",
length : //somelength
}, ...
]
}
To anybody that might be still looking to achieve a full replacement, full disclosure: It might be a bit hacky for some evangelists or even have a performance toll on high traffic apps, but if you really want to do it, you can tap into the toJSON method of the schema like the following:
UserSchema.method('toJSON', function () {
let obj = this.toObject();
obj.books = obj.books.map(
(book) => (Schema.Types.ObjectId.isValid(book.id)) ? book : book.id
);
return obj;
});
What's going on here is basically we're replacing the whole property with the populated result when the book.id has been populated otherwise we just return the original object by checking the validity of the book's id (when populated will be a full bloomed object rather than an id).
What is the current behavior?
To run the script, I'm using babel-node since the script uses es6.
Cannot read property 'Types' of undefined
authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
^
If the current behavior is a bug, please provide the steps to reproduce.
I've defined the schema like this:
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const RecipeSchema = new Schema ({
authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
name: String,
description: String,
photos: [
{
name: String,
path: String,
isMain: Boolean,
alt: String
}
],
ingredients: [
{
name: String,
quantity: Number,
metricType: {
type: String,
enum: [ 'kg', 'g', 'mg', 'l', 'ml', 'unit' ],
default: 'unit'
}
}
],
preparement: String,
isForSell: { type: Boolean, required: true, default: false },
price: Number,
url: String,
portionNumber: Number,
time: Number,
grades: [
{
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
grade: Number,
date: Date
}
],
} );
export default mongoose.model ( 'Recipe', RecipeSchema );
And tried to seed the database with a function like this:
async function insert_recipe () {
const user = await User.findOne ( {} );
await Recipe.create ( {
authorId: user.id,
name: 'some name',
description: 'some description',
ingredients: [
{
name: 'foo',
quantity: 12,
metricType: 'g'
},
{
name: 'bar',
quantity: 50,
metricType: 'g'
}
],
preparement: 'how to do something like this',
isForSell: false,
portionNumber: '5',
time: 20
What is the expected behavior?
It should use the first user's ID that owns the recipe and create the recipe itself on the database.
Please mention your node.js, mongoose and MongoDB version.
I'm using the last versions for all of them in the current moment. (2017-09-15)
After a few trials, I found a solutions with a bit change in the Schema code.
import * as mongoose from 'mongoose';
import { Schema, model } from 'mongoose';
import User from '../models/user';
const RecipeSchema = new Schema ({
authorId: { type: Schema.Types.ObjectId, ref: 'User' },
name: String,
description: String,
photos: [
{
name: String,
path: String,
isMain: Boolean,
alt: String
}
],
ingredients: [
{
name: String,
quantity: Number,
metricType: {
type: String,
enum: [ 'kg', 'g', 'mg', 'l', 'ml', 'unit' ],
default: 'unit'
}
}
],
preparement: String,
isForSell: { type: Boolean, required: true, default: false },
price: Number,
url: String,
portionNumber: Number,
time: Number,
grades: [
{
user: { type: Schema.Types.ObjectId, ref: 'User' },
grade: Number,
date: Date
}
],
} );
export default model.call(require('mongoose'), 'Recipe', RecipeSchema);
So I'm basically importing Schema and model directly instead of using with mongoose.Schema or mongoose.model.
I also had to make a call with model in the end to reference mongoose, like model.call(require('mongoose'), 'Recipe', RecipeSchema);
Now everything worked fine.
Thanks btw!