在express / mongo API的mongo模型中创建列表

时间:2019-05-29 15:20:31

标签: node.js mongodb express mongoose

我有一个具有两种模型的api,分别是“用户”和“书籍”,我希望能够在“用户”模型中创建喜欢的书籍清单,怎么办?

我认为您可以在用户模型中列出一本书的清单,但是我真的不知道在mongo模型中应该如何做,或者该方法是什么样的

有我的模特:

用户模型

const schema = new Schema({
    username: { type: String, unique: true, required: true },
    hash: { type: String, required: true },
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    email: { type: String, required: false },
    image: { type: String, required: false },
    createdDate: { type: Date, default: Date.now }
});

图书模型

const schema = new Schema({
    BookTitulo: String,
    BookSinopsis: String,
    BookISBN: String,
    BookPortada: String,
    BookGenero: String,
    BookAutor: String,
    BookPaginas: Number,
    BookPuntuacion: Number,
    BookPrecio: Number,
    updatedAt: { type: Date, default: Date.now },
});

以及用户方法:

async function authenticate({ username, password }) {
    const user = await User.findOne({ username });
    if (user && bcrypt.compareSync(password, user.hash)) {
        const { hash, ...userWithoutHash } = user.toObject();
        const token = jwt.sign({ sub: user.id }, config.secret);
        return {
            ...userWithoutHash,
            token
        };
    }
}

async function getAll() {
    return await User.find().select('-hash');
}

async function getById(id) {
    return await User.findById(id).select('-hash');
}

async function create(userParam) {
    // validate
    if (await User.findOne({ username: userParam.username })) {
        throw 'Username "' + userParam.username + '" is already taken';
    }

    const user = new User(userParam);

    // hash password
    if (userParam.password) {
        user.hash = bcrypt.hashSync(userParam.password, 10);
    }

    // save user
    await user.save();
}

async function update(id, userParam) {
    const user = await User.findById(id);

    // validate
    if (!user) throw 'User not found';
    if (user.username !== userParam.username && await User.findOne({ username: userParam.username })) {
        throw 'Username "' + userParam.username + '" is already taken';
    }

    // hash password if it was entered
    if (userParam.password) {
        userParam.hash = bcrypt.hashSync(userParam.password, 10);
    }

    // copy userParam properties to user
    Object.assign(user, userParam);

    await user.save();
}

async function _delete(id) {
    await User.findByIdAndRemove(id);
}

0 个答案:

没有答案