当我运行代码
时 var collection = db.get('categories');
console.log(collection.find().limit(1).sort( { _id : -1 } ));
使用mongodb在nodejs上的我收到错误对象#没有方法'限制' 。我是节点的初学者,并且真的停留在节点的这一部分
这里是用于确定最后一个插入文档的完整代码。
router.post('/addcategory', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var name = req.body.name;
var description = req.body.description;
// Set our collection
var collection = db.get('categories');
// Submit to the DB
collection.insert({
"name" : name,
"description" : description,
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
/******************/
console.log(collection.find().limit(1).sort( { _id : -1 } ));
/*************/
}
});
});
答案 0 :(得分:0)
该方法仍然是异步的,因此您仍然需要将其作为具有.then()
的承诺或回调来调用它。没有方法是同步的并且返回结果。
此外,驱动程序返回的结果是s" Cursor"而不是你期望的对象。您可以迭代返回的游标,也可以使用.toArray()
或类似的转换:
collection.find().limit(1).sort({ "_id": -1 }).toArray().then(function(docs) {
console.log(docs[0]);
});
或者:
collection.find().limit(1).sort({ "_id": -1 }).toArray(function(err,docs) {
console.log(docs[0]);
});
但实际上整个前提并不正确。您似乎基本上想要返回刚刚插入的内容。在您的代码中更正的事件,返回的文档不一定是您刚插入的文档,而是插入到集合中的最后一个文档,这可能是从另一个操作发生的,或者是从另一个源调用此路由。
如果您想要插入的内容,请调用.insertOne()
方法并检查结果:
collection.insertOne({ "name": name, "description": description },function(err,result) {
if (err) {
res.send("There was an error");
} else {
console.log(result.ops)
}
});
.insert()
方法被认为已弃用,但基本上返回相同的内容。需要考虑的是,它们返回insertWriteOpResult
对象,其中ops
属性包含插入的文档及其_id
值,
答案 1 :(得分:0)
这里缺少信息的关键部分是您使用的是Monk,而不是本机的MongoDB Node.JS驱动程序。您对find()
的命令是如何使用本机驱动程序(上面的@BlakesSeven建议的更改用于异步),但Monk的工作方式略有不同。
请改为尝试:
collection.find({}, { limit : 1, sort : { _id : -1 } }, function (err,res) {
console.log(res);
});