![](/img/trans.png)
[英]Removing Objects in one-to-many relationships using Node.js REST API, Mongoose, Express, Angular,
[英]Why are my Mongoose One-To-Many Relationships not associating properly?
有誰知道為什么下面的“用戶”和“帖子”之間的一對多關系(用戶可以有很多帖子)不起作用? 看來我有正確的設置我的貓鼬的關聯,但創建一個新的職位時,它不僅是未分配一個用戶,但用戶本身也沒有任何職位有關。 我不確定在這里我可能做錯了什么。
如果您在下面看到JSON對象,則該對象應具有user
值,表示創建帖子的用戶。 您將在下面的帖子模型中看到,應該創建一個用戶值,但不是。
我究竟做錯了什么?
{
__v: 0
_id: "587ee8f5a99b1709b012ce8f"
createdAt: "2017-01-18T04:03:01.446Z"
message: "This is my first test post!"
updatedAt: "2017-01-18T04:03:01.446Z"
}
問題 :盡管在下面的帖子模型中創建了用戶字段,但為什么在上面的JSON中缺少用戶字段?
// Setup dependencies:
var mongoose = require('mongoose');
// Setup a schema:
var PostSchema = new mongoose.Schema (
{
message: {
type: String,
minlength: 2,
maxlength: 2000,
required: true,
trim: true,
}, // end message field
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
},
{
timestamps: true,
}
);
// Instantiate our model and export it:
module.exports = mongoose.model('Post', PostSchema)
// Setup dependencies:
var mongoose = require('mongoose');
// Setup a schema:
var UserSchema = new mongoose.Schema (
{
username: {
type: String,
minlength: 2,
maxlength: 20,
required: true,
trim: true,
unique: true, // username must be unique
dropDups: true,
lowercase: true,
validate: {
validator: function(username) {
var regex = /^[a-z0-9_]+$/i;
return regex.test(username);
},
message: 'Username may contain only letters, numbers or underscores.',
},
}, // end username field
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}],
},
{
timestamps: true,
});
// Instantiate our model and export it:
module.exports = mongoose.model('User', UserSchema)
注意 :這是提交表單后運行的方法。
// Grab our Mongoose Models:
var User = require('mongoose').model('User');
var Post = require('mongoose').model('Post');
module.exports = {
// Creates a new post for logged in user:
newPost: function(req, res) {
Post.create(req.body)
.then(function(newPost) {
return res.json(newPost);
})
.catch(function(err) {
return res.json(err);
})
}
};
有誰知道我的關聯設置不正確,這就是為什么我沒有在他們各自的字段中顯示任何實際的帖子或用戶的原因?
似乎是我的服務器端控制器正確觸發了,因為帖子實際上是創建的。 但是協會本身並沒有聯系在一起,我不確定我在做什么錯。
我在下面添加一個簡單的答案,以繼續上面的示例。 基本上,@ cdbajorin是正確的,我一直在思考正在進行一些自動化,並且沒有適當地遵循正確的貓鼬命令來實現我想要的結果。
我的問題的解決方案如下:
posts
屬性是一個空數組,而不是mongoose.Schema.Types.ObjectID
,因為對象ID這里沒有存儲無論如何,我誤解是如何工作的。 編碼:
posts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}],
相反,應該簡單地寫成:
posts: [],
服務器控制器中的newPost
方法應作如下修改(有關說明,請參見內聯注釋):
newPost: function(req, res) { // creates new post: Post.create(req.body) .then(function(newPost) { // look up current user based on session ID: // note: session setup not shown in this example. User.findById(req.session.userID) .then(function(user) { // push new post into users.posts array from model setup**: user.posts.push(newPost); user.save(); return res.json(newPost); }) }) .catch(function(err) { return res.json(err); })
這確實解決了生成新帖子的問題,然后將其推送到用戶的posts
數組中(來自UsersSchema
)。
盡管最初的帖子中的問題已解決,但人們可能會質疑這是否是數據庫管理的最佳用途。 如本例所示,在用戶內部存儲帖子會占用大量空間,因為用戶和帖子開始累加。
該帖子最終在數據庫中重復兩次:首先,作為本身在posts
集合中的文檔,其次,作為UserSchema
內的posts
數組中的UserSchema
。
更好的解決方案是將帖子保留為posts
集合中的唯一文檔,但是將會話信息中的userID添加到其中。 然后,如果由於某種原因需要所有用戶的帖子,則基於userID查詢Posts集合將返回為其分配了該userID的所有帖子。 然后,數據庫中僅存在一個帖子副本,而不是兩個。
**附加說明:修改現有文檔的另一種方法是使用實例方法,將實際方法插入用戶模型(Schema)文件中,並在需要時調用:
例如,在上面的UserSchema
模型中的module.exports
行之前插入以下代碼,可以在需要時方便地訪問此功能:
UserSchema.methods.addPost = function(post) {
this.posts.push(post);
this.save();
return true;
};
要從服務器控制器中調用此實例方法,我們可以按以下方式重新編寫控制器:
User.findById(req.session.userID)
.then(function(user) {
// call our instance method above:
user.addPost(newPost);
return res.json(newPost);
});
該帖子將通過實例方法推入並保存,該實例方法已內置在實例對象本身中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.