用户喜欢并喜欢Mongoose模式中的系统

时间:2018-05-21 18:32:19

标签: node.js mongodb mongoose model schema

我想创建一个包含用户的数据库,这些数据库也可以引用另一个名为" Library"其中有#34;收藏夹"和"喜欢"。我将在这里展示这个想法:

用户模型

const userSchema = Schema({
    username: {type: String, minlength: 4, maxlength: 10, required: true, unique: true},
    email: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    isVerified: { type: Boolean, default: false },
    library: {type: Schema.Types.ObjectId, ref: 'Library'}
}, { timestamps: true});

图书馆模型

    const librarySchema = new Schema({
    likes: [{
        likeId: {type: String},
        mediaType: {type: String}
    }],
    favourites: [{
        favId: {type: String},
        mediaType: {type: String}
    }],
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

请告诉我这是否是实施这些模型的正确方法,还是有更好的方法? 如果我试着打电话

User.findOne({email: 'xxx@xxx.com'}).populate('library').exec(function (err, library)

它找不到任何东西......

图书馆POST请求

router.post('/favourites', passport.authenticate('jwt', {session: false}), function (req, res) {
const favouritesFields = {};
if (req.body.favId) favouritesFields.favId = req.body.favId;
if (req.body.mediaType) favouritesFields.mediaType = req.body.mediaType;
Library.findOne({user: req.user._id}).then(library => {
    if (library) {
        Library.update({user: req.user._id}, {$push: {favourites: favouritesFields}})
            .then(library => res.json(library));
    } else {
        new Library({user: req.user._id, favourites: favouritesFields}).save().then(library => res.json(library));
    }
});
});

用户POST请求

router.post('/signup', function (req, res) {
const {errors, isValid} = validateSignupInput(req.body);

if (!isValid) {
    return res.status(400).json(errors);
}
// Check if email already exists
User.findOne({email: req.body.email}, function (user) {
    if (user) {
        return res.status(400).json({
            title: 'Email already exists'
        });
    }
});
// Create and save the new user
let user = new User({
    username: req.body.username.toLowerCase(),
    email: req.body.email.toLowerCase(),
    password: bcrypt.hashSync(req.body.password, 10)
});
user.save(function (err, result) {
    if (err) {
        return res.status(500).json({
            title: 'An error occurred during the signup',
            error: err
        });
    }
    res.status(201).json({
        title: 'User created',
        obj: result
    });

1 个答案:

答案 0 :(得分:0)

您的问题与您正在进行的查询有关。没有foundUser.library,因为从未添加过。

您正在向库中添加用户,但您并未向用户添加库。如果您在应用中运行以下代码:

Library.find({}).populate("user").exec(function(err, foundLibraries){
    if (err){
        console.log(err);
    } else {
        console.log(foundLibraries);
    }
});

您会看到图书馆有他们的用户"填充时包含整个用户文档作为对象的属性。但是,当您查询用户时,对于foundUser.library不起作用的原因是从未分配过foundUser.library。您知道在创建用户时如何分配电子邮件,用户名和密码,您必须对库属性执行相同操作。或者,在您的情况下,由于库仅在用户之后创建,因此您只需在创建/保存库的回调中设置user.library的值。

相关问题