mongodb 比较愿望清单上列出的项目并显示推荐

fquxozlt  于 2023-03-01  发布在  Go
关注(0)|答案(1)|浏览(95)

我想比较不同用户的愿望清单项目(书籍),并从对方的愿望清单推荐书籍。
用户A的愿望列表=[“项目1”,“项目2”,“项目3”,“项目4”];用户B的愿望列表=[“项目2”,“项目4”,“项目5”,“项目6”];我想比较愿望清单并返回它们之间的共同项目。由于A和B具有共同的项目2和项目4,所以我想向B推荐项目1 '和'项目3 ',向A推荐'项目5 '和'项目6 '。
这是我的数据库的模型

const mongoose = require("mongoose");

const BookSchema = mongoose.Schema({
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  ownerName: {
    type: String,
    required: true,
  },
  wishListedBy: [
    {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "User",
    },
  ],
  isSold: {
    type: Boolean,
    default: false,
  },
  bookName: {
    //name of book
    type: String,
    required: true,
  },
  subject: {
    //subject -> Engineering subject
    type: String,
    required: true,
  },
  branch: {
    type: String,
    required: true,
  },
  price: {
    //price of the book
    type: Number,
    required: true,
  },
  condition: {
    //condition of the book ->New or Used
    type: String,
    required: true,
  },
  priceType: {
    //negotiable->Fixed, Negotiable, Price on call, Don
    type: String,
    required: true,
  },
  mrp: {
    //MRP of book
    type: Number,
    required: true,
  },
  selectedFile: {
    type: String,
  },
  author: {
    type: String,
    required: true,
  },
  tags: [String], //tags for book
  noOfPages: {
    //no of pages in the book
    type: Number,
    required: true,
  },
  edition: {
    //edition of the book
    type: String,
    required: true,
  },
  description: String, //description of the book
  createdAt: {
    //created At
    type: Date,
    default: Date.now(),
  },
  updatedAt: {
    //created At
    type: Date,
    default: Date.now(),
  },
});

const Book = mongoose.model("Book", BookSchema);

module.exports = Book;
k4emjkb1

k4emjkb11#

假设这些项引用Book.bookName属性:

const wishlistA = ['item1', 'item2', 'item3', 'item4'];
const wishlistB = ['item2', 'item4', 'item5', 'item6'];

const recommendationsA = wishlistB.filter(i => !wishlistA.includes(i));
const recommendationsB = wishlistA.filter(i => !wishlistB.includes(i));

const resA = await Book.find({ bookName: { $in: recommendationsA } });
const resB = await Book.find({ bookName: { $in: recommendationsB } });

相关问题