I have a User model:
const userSchema = new Schema({
username: String,
email: String,
_id: generated
})
and a Project model:
const projectSchema = new Schema({
owner: { type: Schema.Types.ObjectId, ref: 'User' },
name: String,
_id: generated
})
I am using a request to get all projects, and would like to then populate the 'owner' field of each project with the corresponding user (or, even better, their username)
Project.find()
.populate('owner')
.then((allProjects) => {
console.log(allProjects);
res.status(200).json(allProjects);
})
The response from the find(), as seen in the console.log() is an array of objects, on which populate seems to have had no effect:
[{
_id: 4kal5mah5lam6la2lam40am3,
owner: 28eqo29roqi5lqmdka91ma01,
name: Project1
},
{
_id: 0akm40am593na7n4fnau25a,
owner: 85jan5l60oq23la1p07d8q2,
name: Project2
}]
I've tried many things with the populate call and its parameter but to no effect. The code runs, just doesn't populate the field. Any ideas?
Many thanks!
Related
I have an object with the below structure:
Order: [
{
id: '001',
type: '',
status: '',
users: [
{
OrderId:'001',
userId: 'String',
user: {
email: 'string',
givenName: 'Name',
lastName: 'LastName',
phone: 'string',
},
},
],
},
the order is of type Order[] and users of type UserData[]
type Order
#model
#key(fields: ["organizationId", "id"])
#auth(
rules: []
) {
id: ID!
type: OrderType
status: OrderStatus
userConnections: [UserOrderConnection] #connection(keyName: "byOrder", fields: ["id"])
organizationId: ID!
}
type UserOrderConnection
#model
#key(fields: ["organizationId", "id"])
#key(name: "Order", fields: ["OrderId"], queryField: "userOrderByOrder")
#auth(
rules: []
) {
id: ID!
accepted: Boolean
OrderId: ID!
Order: Order #connection(fields: ["organizationId", "id"])
userId: ID!
user: UserData
}
Whenever I try to get the list of users per order :
let users = this.Order.users
it says that: users don't exist on type Order[], can anyone explain for me why.
Order is an array of objects, you need to get the first element like Order[0] then access .users
let users = this.Order[0].users
A good refresher might help here; How can I access and process nested objects, arrays or JSON?
Order is an Array containing objects. To access users you would need to access item at index [0] if it has property ?.users.
this.Order[0]?.users
I have the following schema:
const userSchema = new Schema({
...,
categories: [
{
name: {
type: String,
required: true
},
products: [
{
type: mongoose.Types.ObjectId,
required: false,
ref: 'Product'
}
]
}
],
...
}
I want to get all the products a user have.
I have seen more questions about this topic but I don't get it to work.
If you entered your data correctly you can do like this:
let result = await User.findById(id).populate("categories.products").lean()
I need to save a json in a property of my schema, my schema:
export default class ListSchema {
static schema = {
name: 'Listas',
primaryKey: 'id',
properties: {
id: 'string',
name: 'string',
contents: 'string', // I need to save here, currently I left string
}
}
}
code that saves the list:
async function SaveList() {
const data = {
id: String(Date.now()),
name: List,
contents: JSON.stringify(AllTask) // I need to save json here
}
const realm = await getRealm()
realm.write(() => {
realm.create('Listas', data)
})
}
my json n has a definite size, and it goes something like this:
[{id: 'value', name:'value'}, {id: 'value', name:'value'} ...]
what should my schema look like?
I'm using Realmdb in production with React Native and had the same doubt some time ago.
Basically you have two ways to do it.
The first and the more simple is convert your schema using JSON.stringify and save it in your field with type string, (Like you did) but when you wish get this value again, you will to convert again using JSON.parse, is boring but works well you have just to remeber.
The second option is create another schema and use it to insert values with object format.
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
cars: {type: 'list', objectType: 'Car'},
}
};
Above, we have two schema and if we insert a new data we have to do something like this.
realm.write(() => {
realm.create('Person', {
name: 'Joe',
// nested objects are created recursively
car: {make: 'Honda', model: 'Accord', drive: 'awd'},
});
});
This way is more eficient but is more hard to maintain the code.
Today we use the option 1, because is more simple and just one schema.
I hope that it help you.
I'm trying to remove an index from my mongoDB collection in node.js application using mongoose. I tried using model.collection.dropIndex("username") but it gives me an error UnhandledPromiseRejectionWarning: MongoError: index not found with name [username].
Here is my Schema
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var userTable = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, required: true },
username: { type: String },
salt: { type: String },
passwordHash: { type: String },
email: { type: String, unique: true, required: true },
sessionToken: { type: String },
dateCreated: { type: String, default: new Date().toString() },
loginHistory: [String]
});
module.exports = mongoose.model("userTable", userTable);
When I perform the query in mongo shell from the terminal using command db.usertable.find({}), I can see that the results still have username field. I also tried after removing the username field from schema file, but even that didn't help.
Thanks in advance.
This drops all the indexes of the collection except for the object id
db.collection.dropIndexs();
to delete a certain index
first type the command
db.collecction.getIndexes();
You will see something like above the in the red square is the index name .
db.collection.dropIndex( { "indexname": 1 } )
Creating an index using a unique name:
db.collection('users')
.createIndex(
{ email: 1 },
{ unique: true,
name: 'users.email.unique_index' }, // here we set index name
);
and then drop the index using it's name:
db.collection('users').dropIndex('users.email.unique_index');
I am using mongo and mongoose and I am trying to model my app.
I have the following models: ProductA, ProductB and ProductChat.
Each Product can have many Chats. Each chat is related to one and only product (A or B).
I'd like ProductChat to have a reference to the relevant product document. I thought about adding productType, productId fields to ProductChat:
const ProductChatSchema = new Schema({
...
...
productType: {
type: 'String',
required: true,
enum: [ 'A', 'B' ]
},
product: {
type: Schema.Types.ObjectId,
required: true,
ref: '???' // Ref to what?
},
...
...
});
But I don't know what to put on 'ref'...
I'd like to avoid adding productAId, productBId fields on ProductChat because there might be many products.
Any idea how to do it correct?
As there are many products, give ProductChat ref to ProductsA(B, C..) collection in an array.
const productA = new Schema({
ProductChatIds: [{
type: Schema.Types.ObjectId,
ref: 'ProductChat'
}]
});
const productB = new Schema({
ProductChatIds: [{
type: Schema.Types.ObjectId,
ref: 'ProductChat'
}]
});
ref field means in which collection the id mentioned is gonna be searched for. So, you have to refer to the collection.
For example:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);