Sails.js模型报错:如何在User模型中添加存储Partner ObjectId数组的like字段?
Hey there! Let's walk through setting up the like field in your User model to store an array of Partner ObjectIds, then troubleshoot why your server won't start.
Step 1: Correct User Model Configuration
In your api/models/User.js, define the like field as an array that references the Partner model. Waterline (Sails' ORM) handles ObjectId mapping automatically when using the model attribute inside an array:
module.exports = { attributes: { // Your existing User fields (example) email: { type: 'string', required: true, unique: true }, password: { type: 'string', required: true }, // The new "like" field like: { type: 'array', defaultsTo: [], // Set empty array as default to avoid null issues items: { model: 'Partner' // References the Partner model } } } };
Make sure your api/models/Partner.js exists (even with basic attributes) so Waterline can recognize the association:
module.exports = { attributes: { // Example Partner fields name: { type: 'string', required: true }, // Optional: Add a reverse association if needed likedByUsers: { collection: 'user', via: 'like' } } };
Step 2: Troubleshoot Server Startup Errors
If your server won't start after adding this field, here are the most common issues to check:
- Typos or Case Sensitivity: Sails model names are case-sensitive by default. Ensure you're using
'Partner'(capital P) in themodelattribute, matching the filenamePartner.js(notpartner.js). - Missing Partner Model: If you haven't created the Partner model yet, Waterline will throw an error because it can't find the referenced model. Double-check
api/models/Partner.jsexists. - Database Adapter Mismatch: If you're using MongoDB, ensure your
config/datastores.jsis configured with the correct adapter (sails-mongo). For SQL databases, array associations work differently—you might need a join table instead of a direct array field. - Old Sails Version Syntax: If you're using Sails v0.12 instead of v1+, the array association syntax is slightly different. For v0.12, use:
like: { collection: 'partner', via: null // No reverse association needed } - Invalid Default Value: Avoid setting
defaultsTotonullfor array fields—use an empty array[]instead to prevent validation errors on server start. - Check Error Logs: Always look at the exact error message in your terminal! It will tell you exactly what's wrong (e.g., "Unknown model: Partner" or "Invalid attribute configuration").
Step 3: Test the Setup
After fixing any issues, start your server with sails lift and test adding a like:
// Example: Add a Partner's ID to a User's like array await User.updateOne({ id: 'user-id-123' }) .set({ like: [...existingLikes, 'partner-id-456'] });
内容的提问来源于stack exchange,提问作者Zhen Liu

