Mongoose计数函数获取文件的索引号
问题描述:
我在写一个应用程序,它将文档存储在MongoDB数据库中。我想要一个索引号与每个自动生成的文档相关联。Mongoose计数函数获取文件的索引号
我想计算当前在数据库中的文档数量并设置索引号。那么如何使用Mongoose.js计数函数来实现呢?还是有更好的方法来做到这一点?
这是我document.js文件:
var mongoose = require('mongoose');
var DocSchema = new mongoose.Schema({
Title: String,
Date: Date,
Author: String,
});
mongoose.model('Doc', DocSchema);
答
您将需要也是一个index
字段添加到架构这个工作。
var mongoose = require('mongoose');
var DocModel = mongoose.model('Doc');
var newDoc = new DocModel();
newDoc.Title = 'Title of Book';
newDoc.Date = new Date();
newDoc.Author = 'Author Name';'
DocModel.count().exec(function(err, count){
newDoc.index = count;
newDoc.save(function(err, result){
if(err){
console.log('Error saving new document');
console.log(err);
return;
}
console.log('New document created successfully!);
});
});
请参阅编辑并显示如何将代码添加到此! @Matthew Antolovich – OneMoreQuestion
@axc您是否试图将索引设置为架构级别? –
完全是在指数层面@Matthew Antolovich – OneMoreQuestion