我想添加一个类别,如果成功,请将其推荐给用户'采集。这就是我如何做到这一点:
那是我的" dashboard.js"包含类别架构的文件。
var users = require('./users');
var category = mongoose.model('categories', new mongoose.Schema({
_id: String,
name: String,
ownerId: { type: String, ref: 'users' }
}));
router.post('/settings/addCategory', function(req, res, next) {
console.log(req.body);
var category_toAdd = new category();
category_toAdd._id = mongoose.Types.ObjectId();
category_toAdd.name = req.body.categoryName;
category_toAdd.ownerId = req.body.ownerId;
category.findOne({
name: req.body.categoryName,
ownerId: req.body.ownerId
}, function(error, result) {
if(error) console.log(error);
else {
if(result === null) {
category_toAdd.save(function(error) {
if(error) console.log(error);
else {
console.log("Added category: " + category_toAdd);
<<<<<<<<<<<<<<<<<<<THE CONSOLE LOG WORKS GOOD
users.categories.push(category_toAdd);
}
});
}
}
});
这是我的&#34; users.js&#34;包含&#34;用户&#34;的文件架构。
var categories = require('./dashboard');
var user = mongoose.model('users', new mongoose.Schema({
_id: String,
login: String,
password: String,
email: String,
categories: [{ type: String, ref: 'categories' }]
}));
因此,类别add proccess运行良好,我可以在数据库中找到该类别。问题是当我试图将类别推送给用户时。
这一行:
users.categories.push(category_toAdd);
我收到此错误:
Cannot read property "push" of undefined.
我需要再次承认,在推送之前有一个console.log正确打印类别。
感谢您的时间。
答案 0 :(得分:3)
users
对象是Mongoose模型,而不是它的实例。您需要...
category_toAdd = {
_id: mongoose.Types.ObjectId(),
name: req.body.categoryName,
ownerId: req.body.ownerId
};
// Create the category here. `category` is the saved category.
category.create(category_toAdd, function (err, category) {
if (err) console.log(err);
// Find the `user` that owns the category.
users.findOne(category.ownerId, function (err, user) {
if (err) console.log(err);
// Add the category to the user's `categories` array.
user.categories.push(category);
});
});
模型的正确实例才能将类别添加到。
<强> dashboard.js 强>
<PFeed>
<PID> MyProcess </PID>
<Version>1</Version>
<MetaData>
<Id> MyMetadataId </Id>
</MetaData>
<AllFeeds>
<FeedContent>
<Id> FeedContentId </Id>
</FeedContent>
</AllFeeds>
</PFeed>