![](/img/trans.png)
[英]Trying to save nested document in MongoDB using mongoose on Nodejs
[英]Load and save document in mongodb with mongoose
我有运行express作为服务器端框架的节点。
我创建了以下端点:
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*/ });
});
});
});
第一次调用时,它可以工作。 当我第二次调用它时,它失败了。 该请求只是保持待处理状态,并且从save函数调用返回的对象是未定义的。
两个请求中都undefined
req.body._id
。 我尝试连续创建2个新帖子。
我想要做的是检查文档是否存在,是否存在,对其进行更新然后保存,或者创建一个新文档。
我知道存在upsert之类的东西,但是我不能使用它,因为我需要预先保存的中间件来触发,并且它仅在.save
之前触发。
谁能看到错误?
如果将逻辑放在回调中,然后-根据请求查询值创建或查找Post
,并传递回调函数,该怎么办? 只是不要忘记删除此任务: 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);
}
});
一旦我从模型中删除了unique
字段,并将集合拖放到数据库中,我的原始帖子就起作用了。
删除索引可能已经足够了。 参见Leonid Beschastnys的评论;
当您将字段设置为唯一时,Mongoose会在此字段上创建唯一索引。 即使删除了unique:true标志,该索引仍保留在MongoDB中。 删除集合索引应该可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.