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());
Related
Using Express-graphql, mongo/mongoose/ react.
Im Creating a database with Teams, Players, and Matches.
I want to write a mutation for creating a new team, which lists its players given their IDs, but I keep getting errors. I'm a newbie to GraphQL, so explain it accordingly please.
Can you help me populate "players" please?
The Models
const TeamSchema = new mongoose.Schema({
teamName: { type: String },
teamNumber: { type: Number },
inMatchIDs: { type: mongoose.Schema.Types.ObjectId, ref: "Match" },
players: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
});
const UserSchema = new mongoose.Schema(
{
name: { type: String },
wins: { type: Number },
matchesPlayed: { type: Number },
},
{ timestamps: true }
);
The GraphQL Schema
const TeamType = new GraphQLObjectType({
name: "Team",
fields: () => ({
id: { type: GraphQLID },
teamName: { type: GraphQLString },
teamNumber: { type: GraphQLInt },
inMatchIDs: { type: new GraphQLList(MatchType) },
players: {
type: UserType,
resolve(parent, args) {
return parent.players.map((player) => {
User.findById(player.id);
});
},
},
}),
});
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
wins: { type: GraphQLInt },
matchesPlayed: { type: GraphQLInt },
email: { type: GraphQLString },
password: { type: GraphQLString },
token: { type: GraphQLString },
}),
});
The Mutation Schema
createTeam: {
type: TeamType,
args: {
teamName: { type: GraphQLString },
players: { type: GraphQLList(GraphQLID) },
},
resolve(parent, args) {
const team = new Team({
teamName: args.teamName,
players: args.players,
});
return team.save();
},
},
... and the Request / Response
//send request:
mutation {
createTeam(teamName: "champions", players: ["63382ba421b2cbfcd0531f4c", "63382ba421b2cbfcd0531f4c"]) {
teamName
id
teamNumber
players{
name
}
}
}
//Response:
{
"data": {
"createTeam": {
"teamName": "champions",
"id": "63386d0a850a34f9823fd4cd",
"teamNumber": null,
"players": {
"name": null
}
}
}
}
Mongo:
So after a whole day and a half trying to wrap my head around the relationships, here is how I solved it:
The Mongoose model remains unchanged:
const TeamSchema = new mongoose.Schema({
teamName: { type: String },
teamNumber: { type: Number },
inMatchIDs: { type: mongoose.Schema.Types.ObjectId, ref: "Match" },
players: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
});
The TeamType in the Schema, is how the response displays the information and the subfields (see 'players' here) need to be resolved as this:
The TeamType
const TeamType = new GraphQLObjectType({
name: "Team",
fields: () => ({
id: { type: GraphQLID },
teamName: { type: GraphQLString },
teamNumber: { type: GraphQLInt },
inMatchIDs: { type: new GraphQLList(MatchType) },
players: {
type: GraphQLList(UserType),
resolve(parent, args) {
let players = [];
parent.players.map((id, i) => {
players.push(User.findById(id));
});
return players;
},
},
}),
});
But another important syntax to be careful of is the passing of the information in the args of the mutation:
The Mutation
createTeam: {
type: TeamType,
args: {
teamName: { type: GraphQLString },
players: { type: GraphQLList(GraphQLID) }, //no need for [] as GraphQLList spells it out
},
players: { type: GraphQLNonNull(GraphQLList(GraphQLID)) }, // here I am defining that the value for the key 'players' will be a non-nullable list of GraphQLID type
resolve(parent, args) {
const team = new Team({
teamName: args.teamName,
players: args.players, // so that here, the model for "Team" understand that I am passing it Ids
});
return team.save();
},
},
I have 2 collection: Category and book
Book:
const mongoose = require('mongoose');
// eslint-disable-next-line camelcase
const mongoose_delete = require('mongoose-delete');
const { Schema } = mongoose;
const SchemaTypes = mongoose.Schema.Types;
const Book = new Schema({
name: { type: String },
price: { type: Number },
images: { type: Array },
country: { type: String },
author: { type: String },
publicationDate: { type: String },
description: { type: String },
category: { type: SchemaTypes.ObjectId, ref: 'Category' },
date: { type: Date, default: Date.now },
}, {
timestamps: true,
});
Book.plugin(mongoose_delete);
Book.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true });
module.exports = mongoose.model('Book', Book);
Category:
const mongoose = require('mongoose');
// eslint-disable-next-line camelcase
const mongoose_delete = require('mongoose-delete');
const SchemaTypes = mongoose.Schema.Types;
const { Schema } = mongoose;
const Category = new Schema({
name: { type: String, required: true },
image: { type: String },
products: [{ type: SchemaTypes.ObjectId, ref: 'Book' }],
date: { type: Date, default: Date.now },
}, {
timestamps: true,
});
Category.plugin(mongoose_delete);
Category.plugin(mongoose_delete, { overrideMethods: 'all', deletedAt: true });
module.exports = mongoose.model('Category', Category);
and I select all the books received on the list:
{
_id: new ObjectId("623668ac5b1d392b37690cbc"),
name: 'The Godfather',
price: 110000,
country: 'U.S',
publicationDate: '1969',
category: new ObjectId("6238fdf64f60303756b60b20"),
author: 'Mario Puzo',
... : ...
}
And I want to display the category name on the product list, how do I do it?
**like: {{book.category.name}}
{{book.category.image}}
?**
Since you are using Mongoose, you can use populate() method. You can do it like this:
const books = await Books.find().populate('category')
try $lookup (aggregation)
Book.aggregate([{
$lookup: {
from: "Category",
localField: "category",
foreignField: "_id",
as: "category"
}
}]).exec(function(err, students) {
});
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;
};
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 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).