#Sometimes I'm required to use new ObjectId(..) and sometimes not, can't figure out why?

12 messages · Page 1 of 1 (latest)

ripe canopy
#

I have two models:

Building Schema:

@Schema({
  collection: 'building',
})
export class Building {
  @Prop({ type: Types.ObjectId, required: true })
  playerId: Types.ObjectId;
...
}

Town schema:

@Schema({ timestamps: true })
export class Town {
  @Prop({ type: Types.ObjectId, required: true })
  playerId: Types.ObjectId;
...
}

When I'm querying with the buildingModel I'm not required to use new ObjectID
const building = await this.buildingModel.findOne({ playerId });

But when I'm querying with the townModel I am required to use new ObjectId(..)
const owner = await this.townModel.findOne({ playerId: new ObjectId(playerId) });

Without new ObjectId on the townModel, my queries fail. I really want to know the reason

spice hawk
#

Not to help your problem directly, but usually having ids in your schema is meant to reference to another collection. So, you could put it in a ref and have it populate in your queries, i.e. you don't need to write a different query to collect the player info.

#

Also look to see if you've saved an ObjectId or a string in the playerId property in your building collection.

ripe canopy
#

Thank you, using ref: "Player" solved my problem

dense depot
#

I am noticed similar problem while learning.
When I use
import { Types } from 'mongoose';

  subid: Subject[];```
subid type is ObjectId.

But when I use
```@Prop({ type: Types.ObjectId, ref: 'institutes' })
  insid: Institute;```
insid type is string.
Am I missing something?
#

Hi @spice hawk.

spice hawk
#

@dense depot
I believe it should be:

@Prop({ type: [{ type: Types.ObjectId, ref: 'subjects' }] })
  subid: Subject[];
#

I don't use Nest's Mongoose, so my experience with it is not that great. I use Typegoose.

glacial goblet
#

@dense depot don't mention Core Team members or other users that are not involved in the discussion.

#welcome message

dense depot
#

Sorry 😔

glacial goblet