[英]MongoDB insert with Node.js driver
I'm trying to find out why my ReST server won't insert more than one document to a collection. 我试图找出为什么我的ReST服务器不会在一个集合中插入多个文档。
The following works fine, but if I try to create a new, slightly different document, nothing happens. 以下工作正常,但是如果我尝试创建一个稍有不同的新文档,则什么也不会发生。
Cruds.prototype.save = function(collectionName, obj, callback) {
console.log('obj', obj);
this.getCollection(collectionName, function(error, the_collection) {
if( error ) callback(error)
else {
obj.created_at = new Date();
the_collection.insert(obj, {safe: true}, function() {
callback(null, obj);
});
}
});
};
Above, simply checks for the collection and inserts the document. 上面,仅检查集合并插入文档。 Works only once when I start the server and post to it.
当我启动服务器并发布到服务器时,它仅工作一次。 Subsequent posts don't save.
随后的帖子不会保存。 Is the connection auto-closing?
连接会自动关闭吗? Any ideas?
有任何想法吗?
Thanks! 谢谢!
Found the problem. 找到了问题。 After logging, I realized that the ObjectId was not being uniquely generated on insert (which I didn't really expect) and thus creating unique key conflicts.
记录后,我意识到ObjectId并不是在插入时唯一生成的(这并不是我真正期望的),因此会产生唯一的键冲突。 The solution is to pass the ObjectId along with the insert, like so:
解决方案是将ObjectId随插入一起传递,如下所示:
Cruds.prototype.save = function(collectionName, obj, callback) {
console.log('obj', obj);
this.getCollection(collectionName, function(error, the_collection) {
if( error ) callback(error)
else {
obj._id = ObjectID();
obj.created_at = new Date();
var document = merge(schema.user, obj);
the_collection.insert(document, {safe: true}, function(err, result) {
callback(err, result);
});
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.