我试图将嵌套的JSON转换为mongoose文档和子文档,并且无法实现。我搜索了很多网页,找不到任何有用的东西。
Runkit Link:https://runkit.com/codesnooker/5a391097232f800012605983
这是我的代码:
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);
但我想填充fbProfile,以便在项目中使用它时不需要点击db。知道怎么做吗?
答案 0 :(得分:0)
如果架构具有指向另一个集合的引用属性,则可以使用populate
来获取并设置对该父文档的引用。
User.findOne({
email: 'foo@bar.com'
}).populate('fbProfile').exec().then(/* do something */);