我试图在 Stackoverflow 上找到任何类似的问题,但没有成功。我正在努力寻找在两个文档之间创建关系的正确方法。这是一个非常简单的分层类别案例。每个类别可以有一个父项和多个子项。
var categorySchema = Schema({
name: String,
parent: { type: Schema.ObjectId, ref: 'Category' },
children: [{ type: Schema.ObjectId, ref: 'Category' }],
order: Number
});
var Category = mongoose.model('Category', categorySchema);
当我创建一个新类别时,我得到它应该具有的(如果有的话)父级的 _id。我从 POST/PUT 请求中以字符串形式获取此 _id,并使用此 _id 获取类别。提取工作正常,结果我得到了正确的类别。但这正是我纠结的地方,我如何使用 mongoose 查询的返回结果来创建新类别与其父类别之间的关系?
var query = Category.find({'_id': parentCategoryID});
query.select('name');
query.exec(function (err, parentCategory) {
if (!err) {
console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id);
var parent = parentCategory.toObject();
var category = new Category();
category.name = name;
category.parent = Schema.ObjectId(parent._id);
控制台日志 获取 parentCategory: { name: 'Parent Category', _id: 5218dcd6e6887dae40000002 }.. parentCategory._id: undefined
我已经尝试以多种不同的方式设置父属性,但我无法让它工作。也没有找到有关该问题的文档。
非常感谢您在此问题上提供的任何帮助,我希望更多人可以从这个问题的任何答案中受益。
最佳答案
//problem 1: `find` returns a list of results. You just need findById
var query = Category.findById(parentCategoryID);
query.select('name');
query.exec(function (err, parentCategory) {
//Problem 2: don't ignore errors. Handle them first and short-circuit return
if (err) {
console.err(err);
return;
}
console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id);
//problem 3: mongoose will do the right thing with your schema here
//all you need is
var category = new Category();
category.name = name;
category.parent = parentCategory;
//and don't forget
category.save(...callback....);
}
另请注意,如果您有一个模式,并且您分配的内容与该模式不匹配,则 Mongoose 只会丢弃数据,这可能就是您遇到的情况,假设您调用了 category.save()
在某个时候。
关于node.js - 使用 Mongoose 在 MongoDB 中创建关系(在 Node.js 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421023/