我有一个用户和个人资料对象。在用户对象中,它内部有一个名为profile的数组变量(它应该通过ID号作为参考来存储配置文件对象)。它们都是分别成功创建的,但是当我尝试通过用户ID将配置文件添加到用户中并在mongodb控制台上对其进行搜索时,它会显示为空。
代码的相关部分:
var UserSchema = new mongoose.Schema({
username: String,
password: String,
hasProfile: Boolean,
profile: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Profile"
}
]
});
================================================ ===================
var ProfileSchema = new mongoose.Schema({
name: String,
location: String,
profilePic: String,
photoAlbum: {image: String},
statusUpdates: {image: String},
newsFeed: {image: String}
});
================================================ =========
app.post("/socialNetwork/createProfile", isLoggedIn, function(req,res){
var currUser = req.user;
var currUserId = req.user.id;
var currProfile = req.body.profile;
Profile.create({
name: currProfile.name,
location: currProfile.location
});
curUser.profile.push(currProfile.id);
currUser.save();
});
答案 0 :(得分:0)
我认为您必须采用最近创建的配置文件的_id,然后将其推入用户的配置文件数组中,此_id由mongodb创建,与let str2 = str1.replacingOccurrences(of: "\\", with: "")
中的内容不同
因此您可以添加一个回调函数来创建新的配置文件操作,然后从中获取添加的配置文件的_id
currProfile.id
请注意,您在将profile._id推送到个人档案数组时使用
app.post("/socialNetwork/createProfile", isLoggedIn, function(req, res) { var currUser = req.user; var currUserId = req.user.id; var currProfile = req.body.profile; Profile.create({ name: currProfile.name, location: currProfile.location }, function(err, newProfile) { if (err) { // handle error } else { // here we can take the _id from the newProfile and add it to the user currUser.profile = currUser.profile || []; // double check the profile array, as if this is the first time to push an item to it currUser.profile.push(newProfile._id); currUser.save(); } }); });
而不是curUser