DWQA QuestionsCategory: DatabaseJoin table problem of mongoose set
isLishude asked 1 month ago

userSchema

{
  name: String
}

ContentSchema

{
  uid: mongoose.SchemaTypes.ObjectId,
  content: String,
  status: {
      type: Boolean,
      default: true 
  }
}

Now you can use theContentModel.find({status:true})Data returned here Array If you want to replace the uid with the name value of the user table, how do you do here?,

const ObjectId = mongoose.SchemaTypes.ObjectId;
//Association using ref
const userSchema = new Schema({
  name: String,
  addr: {
    type: ObjectId,
    ref: "address"
  }
});

const addrSchecma = new Schema({
  addr: String,
  uid: {
    type: ObjectId,
    ref: "user"
  }
});

const User = mongoose.model("user", userSchema);
const Addr = mongoose.model("address", addrSchecma);

Create data use case:

const usr1 = {
  name: "user_name"
};

//Create data
(async () => {
  const usr = await User.create(usr1);
  const addr1 = {
    addr: "addr1",
    uid: usr._id
  };
  const addr2 = {
    addr: "addr2",
    uid: usr._id
  };

  const ins1 = await Addr.create(addr1);
  const ins2 = await Addr.create(addr2);
  return [ins1, ins2];
})()
  .then(console.log)
  .catch(console.log);

Then obtain and delete the relevant generated user and associated data,

//Here you get the associated data
(async () => {
  const res = Addr.find().populate("uid");
  return res;
})()
  .then(ins => {
    console.log(ins.uid.name);
  })
  .catch(err => {
    console.log(err);
  });
1 Answers
isLishude answered 1 month ago
const ObjectId = mongoose.SchemaTypes.ObjectId;
//Association using ref
const userSchema = new Schema({
  name: String,
  addr: {
    type: ObjectId,
    ref: "address"
  }
});

const addrSchecma = new Schema({
  addr: String,
  uid: {
    type: ObjectId,
    ref: "user"
  }
});

const User = mongoose.model("user", userSchema);
const Addr = mongoose.model("address", addrSchecma);

Create data use case:

const usr1 = {
  name: "user_name"
};

//Create data
(async () => {
  const usr = await User.create(usr1);
  const addr1 = {
    addr: "addr1",
    uid: usr._id
  };
  const addr2 = {
    addr: "addr2",
    uid: usr._id
  };

  const ins1 = await Addr.create(addr1);
  const ins2 = await Addr.create(addr2);
  return [ins1, ins2];
})()
  .then(console.log)
  .catch(console.log);

Then obtain and delete the relevant generated user and associated data,

//Here you get the associated data
(async () => {
  const res = Addr.find().populate("uid");
  return res;
})()
  .then(ins => {
    console.log(ins.uid.name);
  })
  .catch(err => {
    console.log(err);
  });