简体   繁体   English

使用mongoose在mongodb中加载和保存文档

[英]Load and save document in mongodb with mongoose

I have node running with express as the server side framework. 我有运行express作为服务器端框架的节点。

I have created the following endpoint: 我创建了以下端点:

app.post('/post/save', auth.auth, function (req, res) {

Post.findById(req.body._id, function (err, post) {
  post = post || new Post();

  post.author.name = req.user.getName();
  post.author.id = req.user._id;
  post.title = req.body.title;
  post.body = req.body.body;

  post.save(function (err, object) {
    err && res.send(500);
    res.status(200).send({ /*id: object._id*/ });
  });  
});

});

When I call this the first time, it works. 第一次调用时,它可以工作。 When I call this the second time, it fails. 当我第二次调用它时,它失败了。 The request just keeps pending, and the object returned from the save function call is undefined. 该请求只是保持待处理状态,并且从save函数调用返回的对象是未定义的。

req.body._id is undefined in both the requests. 两个请求中都undefined req.body._id I try to create 2 new posts in a row. 我尝试连续创建2个新帖子。

What I want to do is to check if a document exist, if it does, update it and then save it, or create a new document. 我想要做的是检查文档是否存在,是否存在,对其进行更新然后保存,或者创建一个新文档。

I know stuff like upsert exist, but I cant use it because I need the pre-save middleware to trigger, and it only triggers before .save . 我知道存在upsert之类的东西,但是我不能使用它,因为我需要预先保存的中间件来触发,并且它仅在.save之前触发。

Can anyone see the error? 谁能看到错误?

What if you put your logic to a callback, and then - either create or find a Post based on the request query value, passing your callback function? 如果将逻辑放在回调中,然后-根据请求查询值创建或查找Post ,并传递回调函数,该怎么办? Just dont forget to remove this assignment: post.author.id = req.user._id; 只是不要忘记删除此任务: post.author.id = req.user._id;

app.post('/post/save', auth.auth, function (req, res) {
    var callback = function(post) {
      post.author.name = req.user.getName();
      post.title = req.body.title;
      post.body = req.body.body;

      post.save(function (err, object) {
        err && res.send(500);
        res.status(200).send({ /*id: object._id*/ });
      });  
    };

    if (req.body._id) {
        Post.findById(req.body._id, function (err, post) {
            callback(post);
        });        
    } else {
        var post = new Post();
        callback(post);
    }
});

My original post worked, once I removed the unique field from the model, and dropped the collections in the database. 一旦我从模型中删除了unique字段,并将集合拖放到数据库中,我的原始帖子就起作用了。

It might have been enough to drop the indexes; 删除索引可能已经足够了。 see Leonid Beschastnys comment; 参见Leonid Beschastnys的评论;

when you're setting a field to be unique, Mongoose creates an unique index on this field. 当您将字段设置为唯一时,Mongoose会在此字段上创建唯一索引。 This index persist in MongoDB even after removing unique: true flag. 即使删除了unique:true标志,该索引仍保留在MongoDB中。 Dropping collection indexes should resolve your problem 删除集合索引应该可以解决您的问题

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

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