I am trying to covert nested JSON into mongoose document and subdocument and kind of not able to do it. I have searched web a lot and could not find any useful.
我试图将嵌套的JSON转换为mongoose文档和子文档,并且无法实现。我搜索了很多网页,找不到任何有用的东西。
Runkit Link: https://runkit.com/codesnooker/5a391097232f800012605983
Runkit链接:https://runkit.com/codesnooker/5a391097232f800012605983
Here is my code:
这是我的代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema
const FbProfileSchema = new Schema({
fb_id: {
type: String,
required: true,
index: {
unique: true
}
},
first_name: String,
last_name: String,
}, {
toJSON: {
transform: function (doc, ret) {
var key = ret._id.toHexString();
delete ret._id;
ret._id = key;
}
}
});
const UserModel = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
fbProfile: {
type: Schema.ObjectId,
ref: FbProfileSchema
},
});
var FbProfile = mongoose.model('FbProfile', FbProfileSchema);
var User = mongoose.model('User', UserModel);
var json = "{\"fbProfile\":{\"_id\":\"5a38f1aff8920ebf2b098f40\",\"last_name\":\"My Last Name\",\"first_name\":\"My First Name\",\"fb_id\":\"temp_fb_id\",\"__v\":0},\"email\":\"temp.email@gmail.com\",\"__v\":0,\"_id\":\"5a38f1aff8920ebf2b098f41\"}";
var userJSON = JSON.parse(json);
var user = new User(userJSON);
And I am getting the output as follows:
我得到的输出如下:
But I would like to have fbProfile populated also so that I need not to hit db when using it in the project. Any idea how to do so?
但我想也填充fbProfile,以便在项目中使用它时我不需要点击db。知道怎么做吗?
1 个解决方案
#1
0
If a schema has a reference property to another collection then populate
can be used to fetch and set that reference to the parent document.
如果模式具有另一个集合的引用属性,则可以使用populate来获取并设置对父文档的引用。
User.findOne({
email: 'foo@bar.com'
}).populate('fbProfile').exec().then(/* do something */);
#1
0
If a schema has a reference property to another collection then populate
can be used to fetch and set that reference to the parent document.
如果模式具有另一个集合的引用属性,则可以使用populate来获取并设置对父文档的引用。
User.findOne({
email: 'foo@bar.com'
}).populate('fbProfile').exec().then(/* do something */);