anivaishu
anivaishu

Reputation: 25

how to store string as an objectId using loopback

I have a Loopback model of project.json

project.json

"properties" : {
 "users": {
        "type": [
        {
          "user_id": "string"
        }
      ]
    }
}

array of id stored string format

{
    "users" : [
    {
        "user_id" : "5ae319e8ac5718155ca719d0"
    },
    {
        "user_id" : "5ae31a4d770afb158ef6c048"
    }
]}

how to store string as an objectId like this

{
     "users" : [
        {
            "user_id" : ObjectId("5ae319e8ac5718155ca719d0")
        },
        {
            "user_id" : ObjectId("5ae31a4d770afb158ef6c048")
        }
     ]
   }

Upvotes: 1

Views: 1178

Answers (3)

Kamal Trivedi
Kamal Trivedi

Reputation: 239

In Loopback 4 the string can be stored as ObjectId as follow: Define this property in your loopback model file

@property({
        type: "string",
        mongodb: { dataType: "ObjectId" }
    })
    mainId?: string;

Upvotes: 1

Ashwanth Madhav
Ashwanth Madhav

Reputation: 1134

In Project Model

"relations": {
 "user": {
  "type": "belongsTo",
  "model": "user",
  "foreignKey": "id"
}}

In User Model

"relations": {
 "projects": {
  "type": "hasMany",
  "model": "project",
  "foreignKey": "project_user_id"
}}

If there is no relations, You can use

const ObjectId = require('mongodb').ObjectId;
var userId=ObjectId("5ae319e8ac5718155ca719d0")

and create into db.

You can check the type using typeof(userId). It will be an object.

Upvotes: 0

akkonrad
akkonrad

Reputation: 1073

You should consider to define it as a relationship, not a list of objects. Then you can define relation like users, or members. I assume that a project has many users, and a user can belong to many projects. Then, you need to define hasAndBelongsToMany relationship:

Project.hasAndBelongsToMany(User);
User.hasAndBelongsToMany(Project);

You can read more about it here.

Upvotes: 0

Related Questions