在涉及用户的Mongoose Schema中,我们有时会看到类似这样的内容:
var UserSchema = new mongoose.Schema({
followers: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
});
如果在我的代码中某处,我想添加一个关注者,以下两个语句是否相同?
第一种可能性
var aUser = new User();
var anOtherUser = new User();
aUser.followers.push(anOtherUser); //Push the user object
第二种可能性
var aUser = new User();
var anOtherUser = new User();
aUser.followers.push(anOtherUser._id); //Push the id directly
答案 0 :(得分:1)
使用UserSchema
测试代码后,结果相同。
代码1
var aUser = new User();
var anOtherUser = new User();
aUser.followers.push(anOtherUser);
结果,
aUser --> { "_id" : ObjectId("56f49865a09d6dc824343704"), "followers" : [ ], "__v" : 0 }
anOtherUser --> { "_id" : ObjectId("56f49865a09d6dc824343703"), "followers" : [ ObjectId("56f49865a09d6dc824343704") ], "__v" : 0 }
代码2:
var aUser = new User();
var anOtherUser = new User();
aUser.followers.push(anOtherUser._id);
结果:
aUser --> { "_id" : ObjectId("56f49a07c4b56cc0285d2da1"), "followers" : [ ], "__v" : 0 }
anOtherUser --> { "_id" : ObjectId("56f49a07c4b56cc0285d2da0"), "followers" : [ ObjectId("56f49a07c4b56cc0285d2da1") ], "__v" : 0 }
code2代码段是按Mongoose doc将ObjectId
添加到followers
的正确方法。