简体   繁体   English

用nodejs和mongoose插入新条目的最佳实践是什么

[英]What is the best practice to insert new entry with nodejs and mongoose

I have two models: 我有两个模型:

This is the first: 这是第一个:

var CommentSchema = new Schema({
    title: {
        type: String
    },
    owner: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

This is the second: 这是第二个:

var UserSchema = new Schema({
    name: {
        type: String
    },
    comments: [{
        type: Schema.ObjectId,
        ref: 'Comment'
    }]
});

There are really a lot of comments. 确实有很多评论。 So, i add the id of each comment in the array of comment of owner. 因此,我在所有者的评论数组中添加每个评论的ID。 The goal is to create a simple function like "list my comments". 目标是创建一个简单的功能,例如“列出我的评论”。 The comments are verry actually, i use this code to add new comment: 注释实际上是verry,我使用此代码添加新注释:

var comment = ...
comment.title = "title";
comment.owner = req.user
comment.save(function(err) {
    if (err)
        ...
    else {
        User.findOne({ _id: req.user._id }, function (err, tmpUser){
            tmpUser.comments.push(comment);
            tmpUser.save(function(err) {
                if (err)
                    ...
                else {
                    //END
                }
            });
        });
    }
}

How to optimise this code ? 如何优化此代码? Is it possible to optimise directly the model ? 是否可以直接优化模型? Thank you ! 谢谢 !

Why not simply query the Comments collection? 为什么不简单地查询注释集合? If you're worried about the performance when there are a lot of comments, you can (and should) index the owner field. 如果您担心有很多评论时的性能,则可以(并且应该)对所有者字段建立索引。

db.comments.ensureIndex( { owner: 1 } )

And then using mongoose: 然后使用猫鼬:

Comment.find({ owner: req.user._id }, function(err, comments) {
  // do something with comments
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM